Class Initializers


A syntax exists for initializing classes that is similar to array initialization. Any public field or property may be used to initialize a class. The next example demonstrates initializing three objects with public fields of the class.

// Initializers1 - A Demonstration of Class Object Initialization

using System;

class Cat 
{
    public string Name;
    public int Age;

    public override string ToString()
    {
        return "(" + Name + "," + Age + ")";
    }
}

class Program
{
    static void Main()
    {

        Cat Cat1 = new Cat { Name = "Felix", Age = 10 };
        Cat Cat2 = new Cat { Name = "Tom", Age = 5 };
        Cat Cat3 = new Cat { Name = "Top", Age = 2 };


        Console.WriteLine("Cat1 == {0}", Cat1);
        Console.WriteLine("Cat2 == {0}", Cat2);
        Console.WriteLine("Cat3 == {0}", Cat3);
    }
}

The class Cat has two public fields and only a default constructor. In Main(), three cats are declared and initialized. Note how the public fields are used inside braces to initialize the fields. Not only can fields be used, but public properties (to be covered shortly) can also be used in this way. An example of using properties to initialize the class will be given when properties are covered.