Almost 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.
February 8th, 2008 at 10:56 am
Stud mark = new Stud();
mark.Name = “Markâ€;
mark.Hotness = 10;
or..
mark = new Stud()
{ Name = “Markâ€,
Hotness = 10 };
Not really that much shorter is it? 🙂
February 8th, 2008 at 11:01 am
It’s not much shorter but at least you can put it all on one line. Nice
February 8th, 2008 at 11:43 am
Saved 2 lines of code and I think made it easier to read – wow, tough crowd 🙂
February 10th, 2008 at 5:52 pm
It is a tough crowd! I think it’s easier to read in 3 lines as well. still cool to be able to do that though!
February 11th, 2008 at 2:09 am
Stud mark = new Stud(“Marc”, 10);
Even shorter 😉
February 15th, 2008 at 1:00 am
The object analyser is pretty interesting, but i’ll rather use the old method. If you need to initialise 50 variables, I don’t think you would write the code on a single line… 🙂
June 16th, 2008 at 1:37 pm
[…] talked about initializers before, but let’s review anyway. You can use initializers to reduce the amount of work it takes to create […]
November 5th, 2008 at 1:32 am
Imagine an entity that has 50+ properties…
Nibbler would claim he could still do it with one line of code… (just a call to constructor, no less ;))