Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I've been searching for a way to do the following in VB.NET:

 

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 I'd 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 don't 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.

  • Leaders
Posted

I can't say about the MSIL, my guess is that it will come out about the same, but...

Dim Ctrl As Control = Something

Do Until Ctrl Is Nothing
   'Do whatever
   
   Ctrl = Ctrl.Parent()
Loop

You probably don't 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 shouldn't be too different if you do something like this:

Dim C As Control
Dim text As String

If C Is Nothing Then
   text = ""
Else
   text = C.Text
End If

 

I would compile the code and compare the IL if I had time right now... but I don't.

 

Just a note: check out the .Net Reflector. You can actually use it to compile C# and decompile it into VB, and vice-versa.

[sIGPIC]e[/sIGPIC]
Posted

marble_eater's 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.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...