Saturday, April 30, 2011

One line if in VB .NET

Is it possible to do one line if statement in VB .NET? If so, how?

From stackoverflow
  • Just add Then:

    If A = 1 Then A = 2
    

    or:

    If A = 1 Then _
        A = 2
    
  • It's actually pretty simple..

    If CONDITION Then ..INSERT CODE HERE..
    
    codeape : And the Else part?
    Joey : You just put Else at the end.
  • Or

    IIf(CONDITION, TRUE_ACTION, FALSE_ACTION)
    
    peSHIr : And this is an expression, while the question asked for a statement. ;-)
  • You can use the IIf function too:

    CheckIt = IIf(TestMe > 1000, "Large", "Small")
    
  • Use IF().

    Dim Result = IF(expression,<true return>,<false return>)
    

    SEE ALSO:

  • Be careful with the IIf opertor though - it is not always short-circuited and both the true and false expressions are evaluated.

  • At the risk of causing some cringing by purests and c# programmers, you can use multiple statements and else in a one-line if statement in VB. In this example, y ends up 3 and not 7.

    i = 1
    If i = 1 Then x = 3 : y = 3 Else x = 7 : y = 7
    
    hamlin11 : Why go half way??? i = 1 : if i = 1 Then x = 3 : y = 3 Else x = 7 : y = 7

0 comments:

Post a Comment