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.
>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.