Constructor
Learn to define a class constructor.
What is a constructor?
A constructor is a special method that runs automatically when an instance is created with new. It has the same name as the class, no return type, and sets the object's initial state.
Example: class Player { public Player() { ... } }. Here Player() is the constructor. When you write new Player(), memory is allocated first, then this method runs. If you declare no constructor at all, the compiler generates a parameterless default constructor.
Default constructor
If you declare no constructor at all, the compiler generates a parameterless default constructor automatically. So new Book() compiles; fields get the default values for their types (numbers 0, string null, bool false).
But once you declare any constructor, the compiler stops generating the default. If you write a parameterized constructor and still want a parameterless one, you must declare it explicitly. Otherwise new Book() becomes a compile error.
Exercise Add a constructor to the Player class
Add a public string Name { get; set; } property and a parameterless constructor to the Player class. In the constructor body set Name = "Guest";. Inside Main create an instance with new Player() and print Name.
Show example solution
public Player() { Name = "Guest"; }. In Main write Player p = new Player(); Console.WriteLine(p.Name);
Example solution:
using System;
class Player
{
public string Name { get; set; }
public Player()
{
Name = "Guest";
}
}
class Program
{
static void Main()
{
Player p = new Player();
Console.WriteLine(p.Name);
}
}
Test yourself
-
Which is the constructor of the Player class?
class Player { ... }- public void Player() { }
- public Player() { }
- public void CreatePlayer() { }
- public Init() { }
Show answer
public Player() { } — Correct. A constructor has the class name and no return type.
-
Complete the constructor name
class Player { public ____() { Name = "Player"; } }Show answer
class Player { public Player() { Name = "Player"; } } -
Match each constructor feature to its definition
- Same name as class
- Constructor name
- No return type
- Constructor signature
- Called with new
- When it runs
- Initial state
- Purpose of constructor