C# C# Objects Object-Oriented Programming Object Initialization

Graham Atlee
Graham Atlee
2,718 Points

Why use a constructor?

When filling in a class, why initialize the fields inside a constructor when I can just initialize the fields with the desired value at declaration.

example:

public readonly int Width = 8; public readonly int Height = 5;

1 Answer

andren
andren
28,375 Points

If you set Width and Height outside of the constructor then there would be no way of customizing the map when you instantiate it. Let's say I wanted to have multiple stages in the game, each one having a different map. With the code in the video I could simply create three different Map objects with different numbers passed in to the constructor. Like this for example:

Map smallMap = new Map(4, 4);
Map mediumMap = new Map(8, 8);
Map bigMap = new Map(12, 12);

With your code that would not work since the Map class would be hardcoded to always be the same size. Generally speaking a fixed value class tends to be far less useful than one that can be customized to be useful in multiple scenarios.

Also in many cases you won't actually know what the desired value is while coding the class. For example if I decided to make it possible for the player to type in the map size themselves.