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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With