2.6.4 Default Constructors

Default Constructors

The familiar new Player() call uses a constructor with no arguments. C# can supply that constructor implicitly, but only when the class declares no instance constructors.

Recognize the compiler-supplied constructor
Version A: no declared constructor
public class Player
{
    public int NumberOfTurns;
}

For this public class, new Player() uses the implicit public parameterless constructor. NumberOfTurns starts at 0 because it is an integer field. Reference fields normally start at null unless an initializer supplies a value.

Write a parameterless constructor deliberately

This is an alternative Player definition, not a second class to paste beside Version A.

Version B: explicit parameterless constructor
public class Player
{
    public int NumberOfTurns;

    public Player()
    {
        this.NumberOfTurns = 1;
    }
}

The caller still writes new Player(), but Version B runs the authored assignment and finishes with one turn. Parameterless means no parameters; it does not necessarily mean compiler-generated.

Update creation calls when the contract changes

Fix the call by supplying the required information. Do not add an empty constructor just to silence the error if the design requires that information.

Apply the idea
Check your understanding