.NET use IIF to assign value to different variables

685 views Asked by At

Could I (and if so how) do the following in .NET language (more specifically VB.NET):

Dim a,b as Integer
if(somecondition=1,a,b) = 12345

Or any variant with IIF would be fine by me. Basically I'm always assign the same value but never to the same variable..

3

There are 3 answers

0
rskar On BEST ANSWER

What you're asking to do would have been possible in a language that supports pointer types (such as C/C++, or C# in unsafe mode) with dereferencing; VB.NET doesn't do that. The best you got to leverage is local variables, reference types, and (perhaps) ByRef.

If it's a Class, its instantiation is a reference type. Structure and Integer are each a value type.

For most reference types, you could just set a local variable equal to whichever variable was of interest, and then go ahead and set its properties or call its methods confident that the instantiation affected is the one desired. The one exception to this is when the reference is to an immutable type, such as String.

    Dim a, b As New System.Text.StringBuilder()
    Dim sb As System.Text.StringBuilder = If(somecondition = 1, a, b)
    sb.Append("OK!")

Actually, one doesn't necessarily need a local variable with reference types.

    ' Method 2
    Call If(somecondition = 1, a, b).Append("OK!")

    ' Method 3
    With If(somecondition = 1, a, b)
        .Append("OK!")
    End With

For value types (and immutable classes), you're rather stuck. Mostly all one can do is make use of a local variable as a proxy, just as Jon Skeet has suggested.

A pattern I sometimes use myself:

    Dim a, b As Integer
    If True Then
        Dim _v As Integer = 12345
        If somecondition = 1 Then a = _v Else b = _v
    End If

Note the use of If True Then - this is so the lifetime of _v ends at the End If. The "so what" of that is to avoid either: (1) having a long list of temporary variables; or (2) taking the chance of common coding mistakes that involve the reuse of temporary variables. The temporary variable name (e.g. "_v") can then be reused, even as a different data type, because it will be a different variable to the compiler.

2
Jon Skeet On

No, I don't believe there's any way of doing that in VB. Conditional operators (such as If(x, y, z)) are designed to evaluate one expression or the other based on a condition. In other words, it's the result that's conditional, not the use of it.

Just use a normal If statement:

If somecondition Then
    a = 12345
Else
    b = 12345
End If

Or to avoid repeating the value (e.g. if it's a more complicated expression):

Dim value As Integer = 12345
If somecondition Then
    a = value
Else
    b = value
End If
1
Dave Doknjas On

Not in VB, but since assignment in C# returns the value assigned, you can do the following in C# (since you mentioned 'any .NET language'):

int unused = (someCondition ? a = 123 : b = 123);