1
Classes, Properties and Constructors
C#
public class Student
{
public string Name { get; set; } // auto-property
private int _age;
public int Age // property with validation
{
get => _age;
set => _age = value >= 0 ? value : 0;
}
public static int Count { get; private set; }
public Student(string name, int age) // constructor
{
Name = name;
Age = age;
Count++;
}
public override string ToString() => $"{Name} ({Age})";
}
var s = new Student("Rahim", 21);
Console.WriteLine(s); // Rahim (21)
Console.WriteLine(Student.Count); // 1
- Access modifiers:
public,private(default for members),protected,internal(same assembly),protected internal. readonlyfields can be set only in the constructor;constis a compile-time constant.structis a value type;recordgives value-based equality for data classes.