Question

What's the C# equivalent to the With statement in VB?

Possible Duplicate:
Equivalence of “With…End With” in c#?

There was one feature of VB that I really like...the With statement. Does C# have any equivalent to it? I know you can use using to not have to type a namespace, but it is limited to just that. In VB you could do this:

With Stuff.Elements.Foo
    .Name = "Bob Dylan"
    .Age = 68
    .Location = "On Tour"
    .IsCool = True
End With

The same code in C# would be:

Stuff.Elements.Foo.Name = "Bob Dylan";
Stuff.Elements.Foo.Age = 68;
Stuff.Elements.Foo.Location = "On Tour";
Stuff.Elements.Foo.IsCool = true;
 45  126957  45
1 Jan 1970

Solution

 52

Not really, you have to assign a variable. So

    var bar = Stuff.Elements.Foo;
    bar.Name = "Bob Dylan";
    bar.Age = 68;
    bar.Location = "On Tour";
    bar.IsCool = True;

Or in C# 3.0 and above:

    var bar = new FooType
    {
        Name = "Bob Dylan",
        Age = 68,
        Location = "On Tour",
        IsCool = True
    };

    Stuff.Elements.Foo = bar;
2009-07-24

Solution

 9

Aside from object initializers (usable only in constructor calls), the best you can get is:

var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...
2009-07-24