Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

but this code doesn’t work.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading