New Object Instantiation Goodness

I used to write code like this all the time (and used to is highly sub­jec­tive and quite pos­si­bly includes a time frame as recent as 3 min­utes ago):
MyObject obj = new MyObject();
obj.SomeProperty = 1;
obj.AnotherProperty = 2;
obj.YupItsAnotherProperty = 3;
return obj;

With c# 3.0 (which on an unre­lated note doesn’t par­tic­u­larly roll off the tongue in the way that Python 3000 does. We need to fix that. Or have Vanilla Ice write a rap song about c# 3.0: “Rollin’ along in my 3.0, got my nine in my pocket and I’m ready to go”. I digress.), I now have a new option that is so much eas­ier with less typ­ing and a cleaner look:
return new MyObject
{
SomeProperty = 1,
AnotherProperty = 2,
YupItsAnotherProperty = 3
};

How much nicer is that? Less code, more con­cise, eas­ier to type, it’s a win-win-win sit­u­a­tion. I find myself writ­ing 3.0 code in a 2.0 man­ner all the time but I’m start­ing to catch on to the beauty they added in the lat­est release. And I have even scratched the func­tional pro­gram­ming sur­face found in 3.0. It’s all very good stuff. If I ever have to go back to 2.0 or god for­bid, 1.1, it will be kick­ing and scream­ing and whining.

No Comments

Leave a Reply

Your email is never shared.Required fields are marked *