Using inline IF statement vb.net
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"
Related videos on Youtube
Skindeep2366
Updated on November 21, 2020Comments
-
Skindeep2366 over 3 years
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
-
Skindeep2366 over 11 yearsThanks much guess I should go read up on this IIF statement as I have seen it mentioned in other posts...
-
Skindeep2366 over 11 years@Steve I have tried the above which looks right but if you look at my edit you will see what it is saying.. It should be noted that I know that in my example I have not assigned any value to y. In the actual code where this is used y is assigned a value or remains 0.0 Any ideas??? Further it should be noted that my OP was the exact same thing you posted, the problem was not even looked at... Why am I getting a VS flag on the expression???
-
Steve over 11 yearsSorry for the late comment, but y is a value type (not nullable) and the vb compiler complains about IsNot used against a value type, while has nothing to say when you use a reference type like ApplyValue.