VB.NET equivalent to C#?

shaul_ahuva

Member
Joined
Sep 11, 2004
Messages
16
Location
New Cumberland, PA
Ive been searching for a way to do the following in VB.NET:

C#:
for (Control c = someControl; c.Parent != null; c = c.Parent)
{
     /*
	VB For loop syntax does not allow this (as far as I know).  A Do While Loop could be used, but Id rather have the variable go out of scope after the loop is done...
     */
}

//--------------------

Control c = null;
string text = (c != null) ? c.Text : "";
/*
   In VB.NET IIf would break if c is null since IIf is just a function call, and the result of c.Text is just a parameter...
*/

Does anyone know if there are equivalents in VB.NET? I dont know very much about the costs of the various operations in MSIL, but in the above scenarios the number of operations can be significantly more in VB.NET.
 
I cant say about the MSIL, my guess is that it will come out about the same, but...
[VB]
Dim Ctrl As Control = Something

Do Until Ctrl Is Nothing
Do whatever

Ctrl = Ctrl.Parent()
Loop
[/VB]
You probably dont need to worry about Ctrl going out of scope... the reference gets freed anyways, allowing gc to do its thing,
And VB doesnt have the ? operator, but again, the MSIL shouldnt be too different if you do something like this:
[VB]
Dim C As Control
Dim text As String

If C Is Nothing Then
text = ""
Else
text = C.Text
End If
[/VB]

I would compile the code and compare the IL if I had time right now... but I dont.

Just a note: check out the .Net Reflector. You can actually use it to compile C# and decompile it into VB, and vice-versa.
 
marble_eaters version is identical to the IL, but a *fairly* close VB equivalent is to use IIf:

Dim text As String = IIf((Not c Is Nothing), c.Text, "")

I know this is not exact since, due to IIf being a function, all arguments are evaluated, but if you keep this fact in mind then IIf is more in the spirit of the ?: operator.
 
Back
Top