Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple constructors using primary constructor feature in C#?

Tags:

c#

.net

I have a class user with two fields string Name and int Age. I have a primary constructor as below:

public class User(string name, int age)
{
    public string Name { get; init; } = name;
    public int Age { get; init; } = age;
}

how to add one parameter constructor for field string Name and set value of age 18 as default?

I have tried adding another constructor like this:

public User(string name)
{
     Name = name;
     Age = 18;
}

but this code doesn't work.

like image 605
bita rahimkhani Avatar asked Oct 11 '25 12:10

bita rahimkhani


2 Answers

You have to call the primary constructor from other constructors:

public User(string name) : this (name, 18) { }

This is covered in the 3rd paragraph of the documentation on primary constructors.

like image 87
Richard Avatar answered Oct 14 '25 01:10

Richard


you can use overload of your constructor and call the primary constructor in your code. This is how you can do it:

public class User(string name, int age)
{
    public User(string name) : this(name, 18)
    {
    }

    public string Name { get; init; } = name;
    public int Age { get; init; } = age;
}

I hope this answer help you.

like image 23
Behzad Dara Avatar answered Oct 14 '25 01:10

Behzad Dara