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

Xaqron picture Xaqron · Nov 13, 2010 · Viewed 7.8k times · Source

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

Answer

Pieter van Ginkel picture Pieter van Ginkel · Nov 13, 2010

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.