VB.Net With Statement

  • Thread starter Thread starter Rob Shorney
  • Start date Start date
R

Rob Shorney

Hi,

Please could someone let me know if there is a equivalent command for C#

ie
vb.net

with object
..
..
..
end with
 
As the other guys said, there's no direct equivalent of the VB.NET With
command.

You can get something close with the with the C# using keyword, but your
object must support the IDisposable interface
(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html
/frlrfsystemidisposableclasstopic.asp).

Pen p = new Pen(Color.Black);
using(Pen o = p)
{
o.Color = Color.White;
}

No, that's not similar at all - not only does it require the type to
implement IDisposable, but it calls Dispose at the end too.

Insetad, you can just do:

{
Pen o = p;
o.Color = Color.White;
}

or

Pen o = p;
{
o.Color = Color.White;
}

if you want.
 
My intent was more to give an aesthetical equivalent, but yes - your
suggestions are better than mine.
 
You can get something close with the with the C# using keyword

I can't believe how many times I've heard someone say that (the
'second' use of) "using" in C# is somehow similar to VB's "With". As
Jon says, there is absolutely nothing that relates the two concepts.
I could understand a confusion if a "using" block allowed you to omit
the object reference, but that's not the case.
 
there is absolutely nothing that relates the two concepts.

I somewhat disagree. The way that the VB.BET compiler handles the With
statement is to create a hidden local of the same type, assign a reference
to the object, and use the temporary local for the subsequential calls
within the With/End With block.

The solutions that Jon proposed mimic this approach.
 
I'm confused now - Jon's code didn't use "using" at all.

The fact remain:

With X
....
End With

has exactly nothing to do with what is happening in:

using (X)
{
...
}
 
I'm confused now - Jon's code didn't use "using" at all.

As I said in response to his post, his suggestion was better then using the
"using" keyword. So you're right too. My comment was more from the
theoretical point of view. I apologize for the confusion that I may have
created.
 
The C# literature recomend this:

object o = my.data.object
.....
o.actionOne;
o.property = value;
....

and this works quite well.

Pazu
 
Back
Top