New Object Instantiation Goodness

I used to write code like this all the time (and used to is highly subjective and quite possibly includes a time frame as recent as 3 minutes ago):
MyObject obj = new MyObject();
obj.SomeProperty = 1;
obj.AnotherProperty = 2;
obj.YupItsAnotherProperty = 3;
return obj;

With c# 3.0 (which on an unrelated note doesn’t particularly 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 easier with less typing and a cleaner look:
return new MyObject
SomeProperty = 1,
AnotherProperty = 2,
YupItsAnotherProperty = 3

How much nicer is that? Less code, more concise, easier to type, it’s a win-win-win situation. I find myself writing 3.0 code in a 2.0 manner all the time but I’m starting to catch on to the beauty they added in the latest release. And I have even scratched the functional programming surface found in 3.0. It’s all very good stuff. If I ever have to go back to 2.0 or god forbid, 1.1, it will be kicking and screaming and whining.

Leave a Reply

Your email address will not be published. Required fields are marked *