C# Object Initializers
In this chapter you will learn:
- What are C# Object Initializers
- Example for C# Object Initializers
- 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: