Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With block equivalent in C#?

Tags:

c#

.net

vb.net

I know VB.Net and am trying to brush up on my C#. Is there a With block equivalent in C#?

like image 790
Dan Appleyard Avatar asked Jan 26 '09 22:01

Dan Appleyard


People also ask

Is there an equivalent of with in C#?

No, there is not.

What is using keyword in C#?

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.


2 Answers

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...)

like image 147
Jon Skeet Avatar answered Oct 09 '22 07:10

Jon Skeet


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.

like image 20
Gulzar Nazim Avatar answered Oct 09 '22 06:10

Gulzar Nazim