A constructor in C# is a special method inside a
class that runs automatically when you create an object with new.
This page covers Constructor in C#. For a language-agnostic introduction, see Constructor.
Defining a Constructor#
A constructor has the same name as the class and no return type — not even void.
public class Player
{
public string Name;
public Player(string name)
{
Name = name;
}
}Name = name stores the argument on the object so it’s available later.
Creating an Object with a Constructor#
Pass arguments to the constructor inside the parentheses of new.
Player player = new Player("Alice");
Console.WriteLine(player.Name); // AliceDefault Constructor#
If you don’t define a constructor, C# provides a default one with no parameters. Once you define any constructor, the default is no longer provided automatically.
// No constructor defined — this works:
Player player = new Player();
// Constructor defined with a parameter — this no longer works:
Player player = new Player(); // compile errorUsing this#
Inside the constructor, this refers to the current object. It’s useful when the parameter name matches the field name.
public class Player
{
public string Name;
public Player(string name)
{
this.Name = name; // this.Name is the field; name is the parameter
}
}Common Mistakes#
Giving the constructor a return type
Writing public void Player(string name) makes it a regular method named Player, not a constructor. Constructors have no return type at all — not even void.
Misspelling the constructor name
The constructor name must exactly match the class name, including capitalisation. public player(string name) in a class called Player is not a constructor — it’s a method with a different name.
Forgetting to store the parameter
Receiving name as a parameter doesn’t attach it to the object. You must write Name = name (or this.Name = name) explicitly. Forgetting this means the value is lost when the constructor returns.
Calling the constructor directly after object creation
The constructor runs once, automatically, when you write new Player("Alice"). You don’t call it again — and can’t. Trying to call player.Player("Bob") is a compile error.
Resources#
- Constructors (C# programming guide) (external link) — Microsoft Learn
- Constructor (object-oriented programming) (external link) — Wikipedia