Welcome to Professional ASP.NET - Chris Love's Official Blog Sign in | Join | Help

Chris Love's Official ASP.NET Blog

Chris Love's Helpful tips, tricks and pragmatic development knowledge for the ASP.NET world.
Add to Technorati Favorites


ASP Insider Follow Me On Twitter
If Without an If

Any programmer with a few minutes of experience knows how to use an If statement. Of course each language implements the common logical operator slightly differently syntactically, the results are the same. There are variations, such as If Else, IIF, etc.

Today I was doing a little import from a file where I need to set a Boolean flag based on the value of a field in the record. The value of these fields would either be empty or 'Y'. I thought great I will have to put a full If statement in for each of these fields, I felt OCD about this because the code would look a little clunky and let's face it the better you get at programming the more you want to write 'cool' code to show your friends from time to time. This was one such instance.

Now I am sure there are many of you who will see this and say duh, but honestly would most programmers do it this way? I doubt it, and let's face it our code will need to be maintained by someone else in the future and they may not understand this little technique.

My import routine is using a little parsing code via the VB Code Snippet library, which parses each row in a file to an array called field. As I woke up this morning contemplating this task I thought I would try to reduce this code as follows:

MyFlag = (fields(5) = "Y")

Since the MyFlag variable is a Boolean this works great because the result of the (fields(5) = "Y") expression is either True or False.

The more traditional way to do this might look like this:

If fields(5) = "Y" then

  MyFlag = True

else

  MyFlag = False

end if

Or maybe if you are adventurous you could use the famous IIF statement:

MyField = IIf(fields(5) = "Y", True, False)

The point of this is there are many ways to skin a cat and sometimes we need to do something different just to make life interesting!

Posted: Thursday, August 23, 2007 9:20 AM

by Chris Love

Comments

TomJohnsson said:

Are you really still using VB?  C#is better.

# August 24, 2007 10:43 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS