C# Object Initializer Trick (Update1)

by rsutton 19. October 2009 08:29

UPDATE: Nevermind this doesn’t work.  It passes the compiler, but gives a runtime error.  Sorry.

 

Today I found an interesting trick you can do with object initializers that I hadn’t noticed before.

    1 
    2     class MyClass
    3     {
    4         public int Id { get; set; }
    5         public string Description { get; set; }
    6         public List<string> FirstList { get; set; }
    7         public List<string> SecondList { get; set; }
    8     }
    9 
   10     class Program
   11     {
   12         static void Main(string[] args)
   13         {
   14             var mc = new MyClass
   15             {
   16                 Id = 1,
   17                 Description = "One",
   18                 FirstList = new List<string> { "123", "456" },
   19                 SecondList = { "123", "456" }
   20             };
   21 
   22             // works
   23             var l1 = new List<string> { "123", "456" };
   24 
   25             // does not work
   26             List<string> l2 = { "123", "456" };
   27         }
   28     }
   29 

If you noticed when the list of part of class that uses a setter you can use a short cut and leave out the new List<string> portion.  There interesting part is that it doesn’t work by normal assignment as shown on line 26.

The other interesting part is that this works with dictionaries.

    1 
    2     class MyClass
    3     {
    4         public int Id { get; set; }
    5         public string Description { get; set; }
    6         public Dictionary<string, int> FirstDictionary { get; set; }
    7         public Dictionary<string, int> SecondDictionary { get; set; }
    8     }
    9 
   10     class Program
   11     {
   12         static void Main(string[] args)
   13         {
   14             var mc = new MyClass
   15             {
   16                 Id = 1,
   17                 Description = "One",
   18                 FirstDictionary = new Dictionary<string, int> { { "123", 4 }, { "456", 5 } },
   19                 SecondDictionary = { { "123", 4 }, { "456", 7 } }
   20             };
   21 
   22             // works
   23             var d1 = new Dictionary<string,int> { {"123",4}, {"456",7} };
   24 
   25             // does not work
   26             Dictionary<string,int> d2 = { {"123",4}, {"456",7} };
   27         }
   28     }
   29 

Personally I find this useful while writing unit tests.  Quite often I setup objects in a particular state, so any shortcut to make this faster and cleaner is better.

Tags:

Development

Comments are closed

Powered by BlogEngine.NET 1.4.5.0
Theme by Extensive SEO

Profile

Member of the Church of Jesus Christ of Latter-Day Saints, Developer and IT Professional