Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ternary operator in VB.Net

Tags:

vb.net

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.

like image 592
Unbreakable Avatar asked Oct 31 '25 13:10

Unbreakable


2 Answers

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)
like image 77
Jonathan Gilbert Avatar answered Nov 02 '25 02:11

Jonathan Gilbert


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)
like image 41
Steve Avatar answered Nov 02 '25 02:11

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!