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..
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
andInteger
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
.Actually, one doesn't necessarily need a local variable with reference types.
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:
Note the use of
If True Then
- this is so the lifetime of_v
ends at theEnd 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.