January 12, 2007

A Better IIF for VB.NET

After browsing around a while I came across a code snippet that is very useful yet hardly used! I've always been jealous of C#'s easy-to-use ? operator:

if x ? a : b
But I didn't mind using IIF for VB.NET. Anyways, apparently IIF does some nasty typecasting in the background and isn't very Option Strict On friendly. Say hello to the new and improved Generic IIF function:
Public Function IIf(Of T)(ByVal expression As Boolean, _
        ByVal truePart As T, ByVal falsePart As T) As T

  If expression Then
    Return truePart
  Else
    Return falsePart
  End If
End Function

kick it on DotNetKicks.com

2 comments:

Todd Stout said...

Unfortunately, this is still not equivalent to C/C++/Java/C#'s ? operator. What you have done is only prevent the need to cast the result of IIF. The main problem with IIF is that it is a method/function and not a language operator. Therefore, if an expression (not a constant) is given as the second and third arg to IIF, both will be evaluated. This severely limits the utility of IIF in VB.Net

LaNN said...

I agreed with you Todd Stout. Today I am facing a freak error for almost half day to solved it. I am vary tired. It related to IIf, Nothing and DbNull value. My IIF statement very complex:

Me.Enabled = IIf(dr(_ColumnEnabledName).Equals(DBNull.Value), Nothing, IIf(Char.ToUpper(Convert.ToChar(dr(_ColumnEnabledName))) = "Y", True, False)).

I thought my mistake that is related to DbNull, but its not. I simplify the statement until I got this:

IIf(1=1, Nothing, True) or
IIf(True, Nothing, True)

It should be return Nothing is it?
But its not. It return False and thats why my complex statement got trouble.

Now Here I come, I found lots of trouble on IIF logic. I try

IIf(False, True, Nothing)

It should be return Nothing, but it return False. There are many combination. This two Invalid statement only I test.

One more thing I found.

IIF(True, Nothing, Convert.ToChar("asd")) ' will error
' or even
IIF(False, Nothing, Convert.ToChar("asd")) ' also will error

We know that Convert.ToChar("asd") will generate error. However, since IIF statement is True, It should just return Nothing. weather the IIF statement is true or false it will evaluate the Convert.ToChar("asd"). It can't be like that.

Because This statement

If True Then
Return Nothing
Else
Return Convert.ToChar("asd")
End If
' Note that the function data type is Char? which is accept null (Nothing) value to support database nullable functionality.

Will not generate error.

As a conclusion PLEASE don't use IIF. Waste your time.