C# Object Initializers

In this chapter you will learn:

  1. What are C# Object Initializers
  2. Example for C# Object Initializers
  3. Object Initializers Versus Optional Parameters

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;                                                                           
/*  ww w .ja  v  a2s  .  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, // w ww  .j  a va2s  . c om
              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); 

Next chapter...

What you will learn in the next chapter:

  1. Override the GetHashCode method from object
  2. Example for GetHashCode Method
Home »
  C# Tutorial »
    C# Types »
      C# Object
C# Object
C# new operator
C# this Reference
C# Null
C# Nullable Types
C# ToString Method
C# Object Initializers
C# GetHashCode
C# Object Casting and Reference Conversions