Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent for Visual Basic keyword: 'With' ... 'End With'?

In Visual Basic, if you are going to change multiple properties of a single object, there's a With/End With statement:

Dim myObject as Object

// ' Rather than writing:
myObject.property1 = something
myObject.property2 = something2

// ' You can write:

with myObject
   .property1 = something
   .property2 = something2
   ...
End With

I know C# can do it when creating a new object:

Object myObject = new Object { property1 = something, property2 = something2, ...};

But how do I do that if myOject is already created (like what Visual Basic is doing)?

like image 638
Xaqron Avatar asked Nov 13 '10 21:11

Xaqron


Video Answer


2 Answers

You cannot do this in C#.

This feature is specific to VB and the closest you can come in C# is the object initializer like you describe.

like image 154
Pieter van Ginkel Avatar answered Oct 18 '22 16:10

Pieter van Ginkel


@Mark Byers answer is good but the variable x will live after properties are set. And you can't use name x again (in same block).

Try this (And object must be reference type in this sample) :

void Main()
{
    var myObject1 = new Foo();
    var myObject2 = new Hoo();

    //elided...

    {
        var _ = myObject1;
        _.MyPropertyA = 2;
        _.MyPropertyB = "3";
    }

    {
        var _ = myObject2;
        _.MyPropertyX = 5;
        _.MyPropertyY = "asd";
    }
}
like image 37
Cihan Yakar Avatar answered Oct 18 '22 14:10

Cihan Yakar