February 8th, 2008 - by Golgotha

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.

8 Responses to “Initialize Objects with C# 3.0”

1 Mark

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? 🙂

2 Jack @ The Tech Teapot

It’s not much shorter but at least you can put it all on one line. Nice

3 Golgotha

Saved 2 lines of code and I think made it easier to read – wow, tough crowd 🙂

4 ses5909

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!

5 Nibbler

Stud mark = new Stud(“Marc”, 10);

Even shorter 😉

6 Web Design Media

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… 🙂

7 3 C# 3.0 Shortcuts

[…] talked about initializers before, but let’s review anyway. You can use initializers to reduce the amount of work it takes to create […]

8 Vyas Bharghava

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 ;))

mulberry sale spyder womens jacket cheap new balance 574 mulberry outlet cheap new balance 574 arcteryx outlet mulberry sale spyder womens jacket mulberry sale spyder womens jacket mulberry outlet mulberry outlet new balance 574

Popular Articles

Top 10 Commentators


Subscribe to this feed! Subscribe by Email!

Random Bits Podcast

You need to download the Flash player from Adobe

Blogs Worth Reading