Search code examples
c#propertiesinitializer

Setting properties of an instance the same way as object initializer


What i'd like is having an object initializer, but for an instance of object that has already been created. Something like this:

MyClass myObj = MyClass.NewObj();
//...
myObj { prop1 = val1, prop2 = val2, ... prop50 = val50 };

This would be much better than writing:

myObj.prop1 = val1;
myObj.prop2 = val2;
//...
myObj.prop50 = val50;

because you'd get a list of remaining properties (and only properties!) that haven't already been given value (just like with object initializer). Is there a syntax construct that allows this currently? (C# 6.0)


Solution

  • As some have pointed out, there already exists a similar construct, but in VisualBasic (VB With). Currently, there isn't an equivalent statement in C#. We've seen lately some very useful things added to C#, like auto-property initializer, elvis operator etc. so i'm hoping instance-initializer will be added in the future.