How to call one constructor from another in C#? (this, base)
Hello everyone! I started learning C# and encountered a problem when working with constructors. I have a class `Person` with several fields, and I want to create two constructors: one with parameters (name, age, city), and another — only with name and age, which should set the city to a default value ("Moscow").
Here is my code:
```csharp
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
public Person(string name, int age, string city)
{
Name = name;
Age = age;
City = city;
}
public Person(string name, int age)
{
Name = name;
Age = age;
City = "Moscow";
}
}
```
The problem is that I am duplicating code — the assignment of `Name` and
No answers yet.
Log in to leave an answer
Blogs