The following program demonstrates an Example of Object Initializer in C#.
When there is no constructor available for a class, we can use the object initializer. In other words, an object initializer assigns the initial values to the instance variables of a class. The following code shows that the Box class doesn’t have any constructors. Therefore, the objects of the Box class are created using the object initializers.
using System;
namespace BoxClassObjectInitializerDemo
{
class Program
{
static void Main(string[] args)
{
Box b1, b2, b3, b4;
Console.WriteLine("Box 1:");
b1 = new Box { width = 50, depth = 12, height = 30 };
b1.ShowVolume();
Console.WriteLine("\nBox 2:");
b2 = new Box { height = 70, depth = 10, width = 20 };
b2.ShowVolume();
Console.WriteLine("\nBox 3:");
b3 = new Box { depth = 15, width = 20, height = 25 };
b3.ShowVolume();
Console.WriteLine("\nBox 4:");
b4 = new Box { depth = 5, height = 10, width = 15 };
b4.ShowVolume();
}
}
class Box
{
public int width, height, depth;
public void ShowVolume()
{
Console.WriteLine("Width = {0}\nHeight = {1}\nDepth = {2}", width, height, depth);
Console.WriteLine("Volume of the Box is {0}.", width * height * depth);
}
}
}
Output
Further Reading
How to Create Instance Variables and Class Variables in Python
Comparing Rows of Two Tables with ADO.NET
Example of Label and Textbox Control in ASP.NET
One Dimensional and Two Dimensuonal Indexers in C#