views:

144

answers:

1

Is there a ?: operator equivalent in .net? eg in java I can do:

retParts[0] = (emailParts.length > 0) ? emailParts[0] : "";

rather than

if (emailParts.length > 0) {
    retParts[0] = emailParts[0];
} else {
    retParts[0] = "";
}

I'd like to be able to do similar in VB.NET.

+6  A: 

Use the If operator:

' data type infered from ifTrue and ifFalse
... = If(condition, ifTrue, ifFalse)     

This operator was introduced in VB.NET 9 (released with .net Framework 3.5). In earlier versions, you will have to resort to the IIf function (no type inference, no short-circuiting):

' always returns Object, always evaluates both ifTrue and ifFalse
... = IIf(condition, ifTrue, ifFalse)    
Heinzi
+1: Note VB 2008 only - older versions don't support this variation of the If operator.
Dave Cluderay
So essentially If is type safe but only in 3.5+, If is not type safe but is in all versions?
themaninthesuitcase
`If` is type-safe and only available in 3.5+. `IIf` (two "I") is not type-safe and available in all versions.
Heinzi
1) 'IIf' evaluates both sides, try IIf(True, MsgBox("1"), MsgBox("2")), unlike 'If' which is a keyword, not a function. take a look at http://stackoverflow.com/questions/102084/hidden-features-of-vb-net/1120579#1120579 2) 'If' is also used as the ?? cs keyword, i.e. If(Nothing, variable)
Shimmy