Skip to main content

How to Write a Constructor in C#

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Some objects make no sense without certain values: an account without an owner, an order without an item. In C#, a constructor takes those values when the object is created with new, and sets the object up before any other code can use it.

Syntax​

Syntax
class <ClassName>
{
public <ClassName>(<parameters>)
{
<PropertyName> = <parameter>;
}
}

<ClassName> <variable> = new(<arguments>);
PartWhat it does
public <ClassName>(<parameters>)The constructor: named like the class, with no return type
{ <PropertyName> = <parameter>; }Sets up the new object, usually from the values passed in
new(<arguments>)Creates the object and runs the constructor with these values

Microsoft's constructors guide: "A constructor is a method called by the runtime when an instance of a class or a struct is created."

The Example​

An Account needs an owner and an opening balance. Its constructor takes both, and the program opens two accounts.

Prerequisites​

  • The .NET 10 SDK or newer, which runs a single .cs file with dotnet run. This guide uses .NET SDK 10.0.404.

Step 1: Write the Code​

Create a file named main.cs in an empty folder:

main.cs, which creates an Account for Ana with 50 and an Account for Ben with 0 and prints each owner and balance, with an Account class whose constructor takes owner and openingBalance and sets the Owner and Balance properties.

main.cs
Account account = new("Ana", 50m);
Console.WriteLine($"{account.Owner}: {account.Balance}");

Account other = new("Ben", 0m);
Console.WriteLine($"{other.Owner}: {other.Balance}");

class Account
{
public string Owner { get; set; }
public decimal Balance { get; set; }

public Account(string owner, decimal openingBalance)
{
Owner = owner;
Balance = openingBalance;
}
}

The m in 50m makes the number a decimal, the type of Balance.

Step 2: Run It​

Terminal
dotnet run main.cs
Output
Ana: 50
Ben: 0

A zsh terminal where dotnet run main.cs prints Ana: 50 and Ben: 0.

Each new(...) ran the constructor with its own values, so each account started with its own owner and balance.

The command is the same in zsh, bash and PowerShell.

new() Without the Values​

Once a class has a constructor with parameters, new() without them doesn't compile:

main.cs
Account account = new();

class Account
{
public string Owner { get; set; }
public decimal Balance { get; set; }

public Account(string owner, decimal openingBalance)
{
Owner = owner;
Balance = openingBalance;
}
}
Output
/Users/you/demo/main.cs(1,19): error CS7036: There is no argument given that corresponds to the required parameter 'owner' of 'Account.Account(string, decimal)'

The build failed. Fix the build errors and run again.

A class without any constructor gets a parameterless one from C#. Microsoft's instance constructors guide: "If you declare at least one instance constructor in a class, C# doesn't provide a parameterless constructor." That's the point here: an account can't be opened without an owner.

More Than One Constructor​

When an object can start in more than one way, write one constructor for each. With a parameterless constructor added next to the first one, new() worked:

main.cs
Account account = new();
Console.WriteLine($"{account.Owner}: {account.Balance}");

class Account
{
public string Owner { get; set; }
public decimal Balance { get; set; }

public Account()
{
Owner = "Unknown";
}

public Account(string owner, decimal openingBalance)
{
Owner = owner;
Balance = openingBalance;
}
}
Output
Unknown: 0

C# picked the constructor whose parameters match what you pass to new.

Common Mistakes​

MistakeWhat happensDo this instead
new() when the only constructor takes parameterserror CS7036: There is no argument given that corresponds to the required parameter 'owner'Pass the values, or add a parameterless constructor
Giving the constructor a return type, such as public void Account(...)error CS0542: 'Account': member names cannot be the same as their enclosing typeLeave the return type out
Forgetting to set a property in the constructorIt keeps its type's default: Balance stayed 0 in the parameterless constructor aboveSet every property the object needs

Troubleshooting​

SymptomLikely causeFix
CS7036 ... required parameter on a newThe arguments don't match any constructorPass what the constructor asks for
CS0542: ... member names cannot be the same as their enclosing typeThe constructor has a return type, such as voidRemove the return type
A property is empty right after newThe constructor didn't set itSet it in the constructor

FAQ​

Does every class need a constructor?​

No. A class without one still gets a parameterless constructor from C#: the guide says "If a class has no explicit instance constructors, C# provides a parameterless constructor that you can use to instantiate an instance of that class". Write one when the object needs values to start with.

Constructor or property defaults?​

A property default, such as = "Untitled", is the same for every object. A constructor parameter lets each new choose, like the owner of each account.

Conclusion​

A constructor is a method named like the class, with no return type, that runs when new creates an object: take the values the object needs as parameters and set them. Once a class has one, C# no longer adds a parameterless constructor, so new() without arguments is error CS7036 until you write one.

Additional Resources​