How to set initial value for auto-property in C#?
Hello, colleagues!\n\nI recently started learning C# and encountered a situation. I have a class where I use auto-properties. For example, I create a "User" class, and it has an "Age" property. By default, the age should be 18. Here's how I tried to do it:\n\n```csharp\npublic class User\n{\n public int Age { get; set; } = 18; // does this work?\n}\n```\n\nBut I'm not sure if this is correct. In older versions of C# (e.g., 5.0), this syntax didn't compile. Previously, I did it like this:\n\n```csharp\npublic class User\n{\n private int _age = 18;\n public int Age\n {\n get { return _age; }\n set { _age = value; }\n }\n}\n```\n\nBut that's too much code for a simple property. Now I see that in C# 6.0 and later, you can write `public i
No answers yet.
Log in to leave an answer