A new feature of Visual Studio 2008 and it's C# 3.0 is Object Initalizers. This compiler feature can be used to set the values of properties without the need to create a special constructors. Even though you must have 2008 to use this feature, you don't have to target the 3.0 or 3.5 framework as it works just fine with the 2.0 framework.
The following demonstrates an Object Initalizers' use:
1: FooClass BandMember = new FooClass { FirstName = "John" , LastName = "Plant", Instrument = "Computer" };
Notice the syntax is very similar to an array's syntax and as long as the variable is strongly typed, you can initialize the properties in any order. You can also initalize any collection that implements ICollection<T> in the same manner.
1: using System;
2: using System.Collections.Generic;
3:
4: namespace ObjectInitializer
5: {
6: class FooClass
7: {
8: public string LastName { get; set; }
9: public string FirstName { get; set; }
10: public string Instrument { get; set; }
11: }
12:
13: class Program
14: {
15: static void Main(string[] args)
16: {
17: FooClass BandMember = new FooClass { FirstName = "John" ,
18: LastName = "Plant",
19: Instrument = "Computer" };
20:
21: List<FooClass> FooFighters = new List<FooClass>
22: {
23: new FooClass { FirstName = "Dave", LastName = "Grohl", Instrument = "Vocals" },
24: new FooClass { FirstName = "Nate", LastName = "Mendel", Instrument = "Bass" },
25: new FooClass { FirstName = "Taylor", LastName = "Hawkins" , Instrument= "Drums" },
26: new FooClass { LastName = "Shiflett", FirstName = "Chris", Instrument = "Guitar" },
27: BandMember
28: };
29:
30: foreach (FooClass p in FooFighters )
31: {
32: Console.WriteLine("{0},{1} on {2}", p.LastName, p.FirstName, p.Instrument);
33: }
34:
35: Console.ReadLine();
36: }
37: }
38: }
This new feature may not be a world changer, but combined with automatic properties can be a time saver and will help you produce cleaner code.
Remember Me
Page rendered at Thursday, March 11, 2010 7:01:04 AM (Eastern Standard Time, UTC-05:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.