When you create an instance of a class you want to ensure its fields and properties are initialized to useful values. There are several ways to initialize values with constructors being the most common.
Constructor
A constructor does not list a return type and has the same name as the class:
public class Container
{
private int _capacity;
public Container(int capacity) => _capacity = capacity;
}
If no constructor is provided, a default one is generated by the compiler which simply does nothing. All fields will have their default value.
Overloaded Constructor
You can also provide multiple version of your constructor (overloading it) with different parameters.
Field names
By convention field names will often be prefixed with _ so that the local
variables in the constructor do not conflict with (and thus hide access to) the
object's fields. Alternatively, you may use the this. keyword in the
constructor to refer to fields:
public class Container
{
private int capacity;
public Container(int capacity) => this.capacity = capacity;
}
Constructor code re-use
You cannot simply call a constructor from another constructor without using
new so instead the this keyword exists to call another version of the
constructor in an overloaded constructor.
class Score
{
public string _name;
public int _points;
public int _level;
public Score() : this("Unknown", 0, 1)
{
}
public Score(string name, int points, int level)
{
_name = name;
_points = points;
_level = level;
}
}
Field initializers
These fields will be initialized after the memory in the heap has already been zeroed, but before the contructor runs. Meaning the constructor can overwrite these values.
public class Container
{
private int _capacity = 10;
}
Primary Constructor
public class Container(int capacity)
{
private int _capacity = capacity;
}