OOP
Classes and OOP
Build object-oriented programs with C# classes, properties, inheritance, and interfaces.
C# Classes
C# is a fully object-oriented language. Classes support:
- Properties with getters/setters (better than public fields)
- Auto-implemented properties:
public string Name { get; set; } - Constructors (including primary constructors in C# 12)
- Access modifiers:
public,private,protected,internal
Records (C# 9+)
Records are immutable reference types ideal for data classes. They automatically implement equality, ToString, and deconstruction.
Interfaces
Interfaces define contracts. C# 8+ supports default interface implementations.
Example
csharp
using System;
// Auto-properties, constructor
public class Person {
public string Name { get; set; }
public int Age { get; private set; } // read-only from outside
public string Email { get; init; } // init-only (C# 9)
// Computed property
public bool IsAdult => Age >= 18;
public Person(string name, int age, string email) {
Name = name;
Age = age;
Email = email;
}
public override string ToString() => $"{Name} ({Age})";
}
// Record - immutable data type (C# 9+)
public record Point(double X, double Y);
public record Person2(string Name, int Age) {
public bool IsAdult => Age >= 18;
}
// Inheritance
public class Employee : Person {
public string Department { get; set; }
public decimal Salary { get; protected set; }
public Employee(string name, int age, string email, string dept)
: base(name, age, email) {
Department = dept;
}
public virtual decimal CalculateBonus() => Salary * 0.1m;
}
// Interface
public interface IRepository<T> {
T? FindById(int id);
IEnumerable<T> GetAll();
void Save(T item);
void Delete(int id);
}
// Usage
var person = new Person("Alice", 30, "alice@example.com");
Console.WriteLine(person); // Alice (30)
Console.WriteLine(person.IsAdult); // True
var p1 = new Point(3.0, 4.0);
var p2 = new Point(3.0, 4.0);
Console.WriteLine(p1 == p2); // True (record equality)
var (x, y) = p1; // deconstruction
Console.WriteLine($"x={x}, y={y}");Try it yourself — CSHARP