C# language feature:

  • Object and collection initializers

applies to

  • objects, collections

benefit

  • Allows assignment of values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements.

how to use

  • 1) Assign new object specifying property assignments within {} seperated by ,
  • 2) Assign new collection specifying objects within {} seperated by ,

example:

        class Object_Initialization_Example
        {
            public string Name { get; set; }
        }
        Object_Initialization_Example myobject = new Object_Initialization_Example { Name = "Jeff" };
        int[] odddigits = { 1, 3, 5, 7, 9 };  
        List<int> evendigits = new List<int> { 0, 2, 4, 6, 8};