Why Not Make Everything Public?
If anyone can write account.Balance = -5000, the object cannot protect itself. Encapsulation means hiding the data and allowing access only through controlled doors.
Properties
A property looks like a field but runs code when you read or write it.
csharp
class BankAccount
{
private decimal balance; // hidden field
public decimal Balance // property
{
get { return balance; }
private set { balance = value; } // only this class can change it
}
public void Deposit(decimal amount)
{
if (amount <= 0) throw new ArgumentException("Amount must be positive.");
Balance += amount;
}
}
var acc = new BankAccount();
acc.Deposit(100);
Console.WriteLine(acc.Balance); // 100
// acc.Balance = 5; // error: setter is private
Auto-Implemented Properties
csharp
class Person
{
public string Name { get; set; } = ""; // read and write
public int Id { get; } // read only (set in constructor)
public DateTime Created { get; init; } // can be set once, at creation
public int Age => DateTime.Today.Year - Created.Year; // calculated
}
Validation in a Setter with the field Keyword (C# 14)
In C# 14 the field keyword gives you the hidden backing field without declaring it. Needs the .NET 10 SDK.
csharp
class Product
{
public string Name
{
get;
set => field = string.IsNullOrWhiteSpace(value)
? throw new ArgumentException("Name is required.")
: value.Trim();
}
public decimal Price
{
get;
set => field = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value));
}
}
Constructors
A constructor runs when you create an object and sets it to a valid starting state. It has the same name as the class and no return type.
csharp
class Student
{
public string Name { get; }
public int Grade { get; }
public Student(string name, int grade)
{
Name = name;
Grade = grade;
}
public Student(string name) : this(name, 1) { } // chain to the other one
}
var s = new Student("Ana", 5);
Primary Constructors (C# 12)
csharp
class Teacher(string name, string subject)
{
public string Name { get; } = name;
public string Subject { get; } = subject;
public string Describe() => $"{name} teaches {subject}";
}
var t = new Teacher("Raj", "Math");
Console.WriteLine(t.Describe());
Object Initializers
csharp
var p = new Person { Name = "Ana", Created = new DateTime(2020, 1, 1) };
Access Modifiers
| Modifier | Visible to |
public | Everyone |
private | Only the same class (default for members) |
protected | The class and its child classes |
internal | Everything inside the same project |
private protected / protected internal | Combinations for special cases |
Rule of thumb: Make things as private as possible and open them only when needed.
Conclusion
Use properties instead of public fields, validate in setters or constructors and keep members private by default.
Quick Summary: Properties protect data, constructors set a valid start, access modifiers control visibility.