I know VB.Net and am trying to brush up on my C#. Is there a With
block equivalent in C#?
No, there is not.
The using keyword has two major uses: The using statement defines a scope at the end of which an object will be disposed. The using directive creates an alias for a namespace or imports types defined in other namespaces.
Although C# doesn't have any direct equivalent for the general case, C# 3 gain object initializer syntax for constructor calls:
var foo = new Foo { Property1 = value1, Property2 = value2, etc };
See chapter 8 of C# in Depth for more details - you can download it for free from Manning's web site.
(Disclaimer - yes, it's in my interest to get the book into more people's hands. But hey, it's a free chapter which gives you more information on a related topic...)
This is what Visual C# program manager has to say: Why doesn't C# have a 'with' statement?
Many people, including the C# language designers, believe that 'with' often harms readability, and is more of a curse than a blessing. It is clearer to declare a local variable with a meaningful name, and use that variable to perform multiple operations on a single object, than it is to have a block with a sort of implicit context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With