Object Initialization

Constructor method are used to construct new instances of a class. Constructor method are named the same as the class they're in. The constructor is called when the object created.

Example of the constructor is like this.

public Map(int height, int width)
{
    Height = height;
    Width = width;
}

The Map.cs should look like this. For parameters like height and width that couldn't be re-assigned in the future, we could use readonly.

class Map
{
    public readonly int Height;
    public readonly int Width;

    public Map(int height, int width)
    {
        Height = height;
        Width = width;
    }
}

in Game.cs,

class Game
{
    static void Main(string[] args)
    {
        Map map = new Map(8, 5);

        Console.WriteLine(map.Height * map.Width);
        Console.Read();
    }
}

results matching ""

    No results matching ""