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..
Best How To :
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)
If it's a
Class, its instantiation is a reference type.
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
Dim a, b As New System.Text.StringBuilder()
Dim sb As System.Text.StringBuilder = If(somecondition = 1, a, b)
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)
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
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.