Skindeep2366
Skindeep2366

Reputation: 1559

Using inline IF statement vb.net

Brief info on the code is as follows. The code takes a bunch of strings and concants them as follows with a if statement in the middle that decides whether to concant or not on one of them. The problem is the If(Evaluation, "", "") is complaining saying that it must not be nullable or must be a resource.. How do I work around this when the Evaluation simply checks an object to make sure it IsNot Nothing and also that a property in the object is checked as follows:

Dim R as string = stringA & " * sample text" & _
    stringB & " * sample text2" & _
    stringC & " * sameple text3" & _
    If(ApplyValue IsNot Nothing AndAlso ApplyValue.CheckedBox Then ,StringD & " * sample text4" & _
    , NOTHING)
stringE & " * sample text5"

VS is complaining about the applyValue. Any Ideas?

Should be noted that I have tried the following just to see if it would work and VS is rejecting it:

Dim y As Double
Dim d As String = "string1 *" & _
    "string2 *" & _
    If(y IsNot Nothing, " * sample text4", "") & _
    "string4 *"

This is what it is flagging the y with:

  'IsNot' requires operands that have reference types, but this operand has the value type 'Double'.    C:\Users\Skindeep\AppData\Local\Temporary Projects\WindowsApplication1\Form1.vb 13  16  WindowsApplication1

Upvotes: 30

Views: 68936

Answers (1)

Steve
Steve

Reputation: 216273

Use the IIF ternary expression evaluator

Dim R as string = stringA & " * sample text" & _
                  stringB & " * sample text2" & _
                  stringC & " * sameple text3" & _
                  IIf(ApplyValue IsNot Nothing AndAlso ApplyValue.CheckedBox, StringD & " * sample text4", "") & _
                  stringE & " * sample text5"

EDIT: If you use VB.NET from ver 2008 onward you could use also the

IF(expression,truepart,falsepart)

and this is even better because it provides the short-circuit functionality.

Dim R as string = stringA & " * sample text" & _
                  stringB & " * sample text2" & _
                  stringC & " * sameple text3" & _
                  If(ApplyValue IsNot Nothing AndAlso ApplyValue.CheckedBox, StringD & " * sample text4", "") & _
                  stringE & " * sample text5"

Upvotes: 58

Related Questions