C# Object Initializers

Members of an object can be assigned without calling a constructor at creation time.
  1. MyClass myObject = new MyClass() {MyID = 1, MyName = "John Doe"};

Example
  1. class Program
  2. {
  3.     static void Main(string[] args)
  4.     {
  5.  
  6.         //Object initializer
  7.         MyClass myObject = new MyClass() {MyID = 1, MyName = "John Doe"};
  8.  
  9.         int id =myObject.GetMyID();
  10.         string name = myObject.GetMyName();
  11.  
  12.         Console.WriteLine("{0,-3:0}{1:s}",id,name);
  13.     }
  14. }
  15.  
  16. public class MyClass
  17. {
  18.     private int _myID;
  19.     private string _myName;
  20.  
  21.     public int MyID { get; set; }
  22.     public string MyName { get; set; }
  23.  
  24.     public MyClass() { }
  25.  
  26.     public int GetMyID()
  27.     {
  28.         return MyID;
  29.     }
  30.  
  31.     public string GetMyName()
  32.     {
  33.         return MyName;
  34.     }
  35. }
m ant / Mechanical Ant