Tuesday, May 12, 2009

Beware of IIF

Should we use IIF of VB.NET? I would say no, lets validate it why should we not use IIF.

First reason:

In IIF both true and false part are evaluated, Lets evaluate

Create a Button control and copy and paste below code on the button click event,

Dim i As Integer = CInt(IIf(Session("test") Is Nothing, 0, Session("test").ToString()))

Compile and run the application, Click on the Button, you will get below error,

Object reference not set to an instance of an object.

It made me to believe that both the statements (true and false) are executing 0 as well as Session("test").ToString(), 2nd statement (Session("test").ToString()) which is else part shouldn't have executed but it got executed.

This is serious problem when you are checking an object with Nothing.

Now run the below code in C#

int i = (Session["test"] == null ? 0 : Convert.ToInt32(Session["test"].ToString()));

It won't throw any error because it won't go to else part.

Second reason:

Turn Off Option Strict, Copy and paste below code on top of the page
Option Strict Off

Create a Button control and copy and paste below code on the button click event,

Dim blnIIF As Boolean
Dim frmIIF As Form = IIf(blnIIF, "True", 10)

Compile and run the application, Click on the Button, you will get below error,

"Unable to cast object of type 'System.Int32' to type 'System.Windows.Forms.Form"

The above code compiled, which is quite weired. It should have throw error at compile time.

Why it didn't throw error at compile time?

Actually, IIF is a function, its paraemeters and return type are object, therefore while compiling it looses all type checking.

But if you turn on Option Strict, Copy and paste below code on top of the page

Option Strict ON

Now, you will get compile time error.

But in case of C#, below code won't compile

Form f = (blnIIF?"True":10);

Happy Coding :)

No comments:

Site Meter