Initialize Objects with C# 3.0
Friday, February 8th, 2008Almost every object you create needs to be initialized in some way. In C# 3.0 you now have a new shorthand method for doing so called an object initializer.
Here’s some typical code to initialize an object:
Stud mark = new Stud();
mark.Name = "Mark";
mark.Hotness = 10;
Here’s the new C# 3.0 object initializer way:
mark = new Stud() { Name = "Mark", Hotness = 10 };
This does exactly the same thing as the three lines of code above, but in one line! And the IDE (Visual Studio 2008) even helps out with IntelliSence showing you the fields available. Pretty cool eh? If you’re running Visual Studio 2005, then this won’t work.