C# Properties
Properties wrap fields with get and set accessors. Auto properties are shorthand. init makes a value settable only when the object is created, and required forces it.
Example
class User
{
public string Name { get; set; } = "";
public int Age { get; init; }
private int _score;
public int Score { get => _score; set => _score = Math.Max(0, value); }
}
var u = new User { Name = "Ada", Age = 21, Score = -5 };
Console.WriteLine(u.Name + u.Age + u.Score);Exercise
Read accessor keyword.
public int X { ; set; }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.