C# Object Initializers

Description

To simplify object initialization, the accessible fields or properties of an object can be initialized in a single statement directly after construction.

Example

For example, consider the following class, you can instantiate Car objects by using object initializers as follows.


public class Car                                                                              
{                                                                                               
  public string Name;                                                                           
// w ww  . j av  a2 s . c  om
  public bool NewModel; 
  public bool AutoDrive; 

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


// Note parameterless constructors can omit empty parentheses 
Car b1 = new Car { Name="Bo", NewModel=true, AutoDrive=false }; 
Car b2 = new Car ("Bo")     { NewModel=true, AutoDrive=false }; 

Object Initializers Versus Optional Parameters

Instead of using object initializers, we could make Car's constructor accept optional parameters:


public Car (string name, 
              bool newModel = false, //from  w  w  w  .j  a  va 2s. c o  m
              bool autoDrive = false) 
{ 
  Name = name; 
  NewModel = newModel; 
  AutoDrive = autoDrive; 
} 

This would allow us to construct a Car as follows:


Car b1 = new Car (name: "Bo", newModel: true); 




















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor