How to set initial value for auto-property in C#?
Hello everyone! I'm new to C# and encountered this problem. I want my class to have a property that immediately has some default value when an object is created, for example, the number 0 or the string "Not specified". I'm using auto-properties because they are convenient and short.
Here's an example of my class:
```csharp
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
```
When I create an object `Person p = new Person();`, the `Name` and `Age` properties get the default values for their types (`null` for string and `0` for int). But I need `Name` to initially be `"Guest"` and `Age` to be `18`.
I know that this can be done in the constructor:
```csharp
public Person()
{
Name = "Guest";
Age = 18;
}
```
No answers yet.
Log in to leave an answer