I am new to VB.net and want to use ternary operator.
If prefixDt IsNot Nothing AndAlso prefixDt.Rows.Count > 0 Then
Return True
Else
Return False
End If
Myattempt:
Return (prefixDt IsNot Nothing AndAlso prefixDt.Rows.Count > 0) ? True: False
Error: ? cannot be used here.
VB.NET prior to 2008 did not have a ternary operator. It did have a ternary function, IIf(cond, truePart, falsePart), but being a function, both truePart and falsePart would be evaluated before the function decided which to return.
In VB.NET 2008, a new operator was introduced that provides the same functionality as the cond ? truePart : falsePart ternary operator in C-like languages. This operator uses the If keyword and is expressed with function-like syntax:
safeQuotient = If(divisor <> 0, dividend / divisor, Double.PositiveInfinity)
In this example, dividend / divisor in the truePart is safe even if divisor is zero, because if divisor is zero, the truePart is completely ignored, and the division by zero will not occur.
For your example, as was pointed out by @nabuchodonossor, you would only be converting a Boolean value that is already True or False into the same True or False value, but for completeness, you can write it out exactly as @Steve showed:
Return If(prefixDt IsNot Nothing AndAlso prefixDt.Rows.Count > 0, True, False)
It is one liner using the ternary (conditional) operator
return If (prefixDt IsNot Nothing AndAlso prefixDt.Rows.Count > 0, True, False)
But if you need to return immediately you can simply test if the boolean expression is true or false
return (prefixDt IsNot Nothing AndAlso prefixDt.Rows.Count > 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With