Unbreakable
Unbreakable

Reputation: 8084

ternary operator in 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.

Upvotes: 4

Views: 7025

Answers (3)

Rob
Rob

Reputation: 2472

Note there is really no way to do this if you are not doing variable assignment. But you can do something like this.

Label1.Visible = If(1=0,true, false)

C# does it better!

Upvotes: 0

Jonathan Gilbert
Jonathan Gilbert

Reputation: 3840

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)

Upvotes: 5

Steve
Steve

Reputation: 216293

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)

Upvotes: 4

Related Questions