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)?
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.
@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";
}
}
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