Pages

Tuesday, September 30, 2008

Type Initializers in C# 3.0

This is really cool. C# version 3.0 has a new syntax for instantiating an object as well as setting a bunch of initial properties and values on it. This works for regular types as well as lists and dictionaries.

Look at this sample code below.


//
// Regular object initialization
//

// C# 2.0 and earlier

SaveFileDialog dialog = new SaveFileDialog();
dialog.CheckFileExists = false;
dialog.CheckPathExists = true;
dialog.OverwritePrompt = false;

// C# 3.0. Not a huge savings on lines, but less language clutter over all

var dialog = new SaveFileDialog
{
CheckFileExists = false,
CheckPathExists = true,
OverwritePrompt = false
};

// --------------------------------

//
// List initialization
//

// C# 2.0 style

List<string> stringList = new List<string>();
stringList.Add("FOO");
stringList.Add("BAR");
stringList.Add("BAZ");
stringList.Add("BANG");

// C# 3.0 style
var stringList = new List<string>{ "FOO", "BAR", "BAZ", "BANG" };


// --------------------------------

//
// Dictionary initialization
//

// C# 2.0 style

Dictionary<int, string> employeeNameMap = new Dictionary()<int, string>();;
employeeNameMap .Add(1, "Sally");
employeeNameMap .Add(2, "Tim");
employeeNameMap .Add(3, "Joe");
employeeNameMap .Add(4, "Jane");

// C# 3.0 style

var employeeNameMap = new Dictionary<int, string>
{
{1, "Sally"}, {2, "Tim"}, {3, "Joe"}, {4, "Jane"}
};




Reference URL: CSharp Type Initializers in C# 3.0