views:

140

answers:

5

I am a C# programmer but dabbling in VB.Net because everybody else in my team uses it. In the interests of professional development I would like to shrink the following If... Else... statement.

If cmd.Parameters("@whenUpdated").Equals(DBNull.Value) Then
    item.WhenUpdated = Nothing
Else
    item.WhenUpdated = cmd.Parameters("@whenUpdated").Value
End If

I appreciate examples are already available however I can not get it working for this specific case.

Cheers, Ian.

+2  A: 
item.WhenUpdated = Nothing
If cmd.Parameters("@whenUpdated").Equals(DBNull.Value) Then
    item.WhenUpdated = cmd.Parameters("@whenUpdated").Value
End If

Only 1 line, but still shorter.

The IF function is definitely the shortest, but not the most readable.

Dustin Laine
You could also put the =Nothing at the declaration, so Dim WhenUpdated as Date = Nothing. That'd save another line :-)
CResults
I can't do that @CResults as it is a data object. ;-)
Ian Roke
Well I could... :-)
Ian Roke
+3  A: 

Similar to the ternary operator in C#, VB has the IIF function.

item.WhenUpdated = IIF(cmd.Parameters("@whenUpdated").Equals(DBNull.Value),
                            cmd.Parameters("@whenUpdated").Value, 
                            Nothing)

If the first argument (the boolean expression) evaluates to true, then the second argument is returned from the function. If the first argument is false, then the third argument is returned.

womp
The IIf function doesn't short-circuit and returns type Object, which must be cast. As long as you're using VB2008, it's better to use the new If ternary operator instead.
Dan Story
Good to know. I dropped VB a few years back and haven't done much with it since.
womp
I'm turning green with envy.
Dan Story
Some people have all the luck!
Ian Roke
+6  A: 

Use If as a function rather than a statement:

item.WhenUpdated = If(cmd.Parameters("@whenUpdated").Equals(DBNull.Value), cmd.Parameters("@whenUpdated").Value, Nothing)
Dan Story
Works exactly as required. Many thanks.
Ian Roke
MarkJ
A: 

One less line

item.WhenUpdated = Nothing
If cmd.Parameters("@whenUpdated").Equals(DBNull.Value) Then
    item.WhenUpdated = cmd.Parameters("@whenUpdated").Value
End If
Samuel Carrijo
A: 

Use the operator If(...) if you want short-circuiting behavior.

Use the function IIf(...) if you don't want short-circuiting behavior.

Chris Dwyer