Object Initializers - CSharp Custom Type

CSharp examples for Custom Type:Object Initializer

Introduction

To simplify object initialization, 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 Animal
{
  public string Name;
  public bool LikesCarrots;
  public bool LikesHumans;

  public Animal () {}
  public Animal (string n) { Name = n; }
 }

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

 // Note parameterless constructors can omit empty parentheses
Animal b1 = new Animal { Name="a", LikesCarrots=true, LikesHumans=false };
Animal b2 = new Animal ("a")     { LikesCarrots=true, LikesHumans=false };

Related Tutorials