Friday, October 10, 2008

[C#] Object Creation with Property Initialization

So a colleague of mine showed me a nice simple way in C# to both create and initialize an object in one step. I thought this was really neat syntax since it both saves lines of code and also saves some execution as the object is initialized with a value instead of a default which is THEN changed.

So something like this:
Rectangle myRec = new Rectangle();
myRec.Width = 50;
myRec.Height = 50;
Can become:
Rectangle myRec = New Rectangle() { Width=50, Height=50 };


There are some restrictions though:
  • Can only initialize properties or fields accessible by the object being initialized.
  • This means that you cannot set attached properties in this manner [ie. Canvas.Top], as these properties can only be set with the SetValue function.
  • The assignments in the initializer is treated the same as assignments to members of the field/property.

See here for a little more
And this msdn page

.

No comments: