CSharp/C# Tutorial - C# Object Initializers






Any accessible fields or properties of an object can be set via an object initializer directly after construction.

For example, consider the following class:


public class Person { 
    public string Name; 
    public bool IsWorking; 
    public bool HasChild;
    //from   ww  w  . j av  a 2 s  .c o  m
    public Person () {} 
    public Person (string n) { 
       Name = n; 
    } 
} 

Using object initializers, you can instantiate Person objects as follows:


// Note parameterless constructors can omit empty parentheses 
Person b1 = new Person { Name="Jack", IsWorking=true, HasChild=false }; 
Person b2 = new Person ("Jack") { IsWorking=true, HasChild=false }; 




Object Initializers Versus Optional Parameters

We can make Person's constructor accept optional parameters:


public Person (string name, bool IsWorking = false, bool HasChild = false) { 
    Name = name; 
    IsWorking = IsWorking; 
    HasChild = HasChild; 
} 

This would allow us to construct a Person as follows:


Person b1 = new Person (name: "Jack", IsWorking: true);