C# Course

C# OOP: Classes, Interfaces, Inheritance

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

Classes and Properties

public class Person {
    // Auto-properties
    public string Name { get; set; }
    public int Age { get; private set; }

    // Constructor
    public Person(string name, int age) {
        Name = name;
        Age = age;
    }

    // Method
    public void Introduce() {
        Console.WriteLine($"Hi, I am {Name}, age {Age}");
    }
}

var person = new Person("Alice", 30);
person.Introduce();   // Hi, I am Alice, age 30
person.Name = "Bob";  // OK
// person.Age = 25;   // ❌ private setter

Inheritance

public class Animal {
    public string Name { get; }
    public Animal(string name) => Name = name;
    public virtual void Speak() => Console.WriteLine($"{Name} makes a sound");
}

public class Dog : Animal {
    public Dog(string name) : base(name) {}
    public override void Speak() => Console.WriteLine($"{Name} barks!");
}

Animal a = new Dog("Rex");
a.Speak(); // "Rex barks!" — polymorphism

Interfaces

public interface IFlyable {
    void Fly();
    string Type => "flying object"; // default implementation (C# 8+)
}

public class Bird : Animal, IFlyable {
    public Bird(string name) : base(name) {}
    public void Fly() => Console.WriteLine($"{Name} is flying!");
}

Abstract Classes

public abstract class Shape {
    public abstract double Area();
    public void PrintArea() => Console.WriteLine($"Area: {Area():F2}");
}

public class Circle : Shape {
    private double _r;
    public Circle(double r) => _r = r;
    public override double Area() => Math.PI * _r * _r;
}

var c = new Circle(5);
c.PrintArea(); // Area: 78.54

Records (C# 9+)

public record Point(double X, double Y);

var p1 = new Point(1.0, 2.0);
var p2 = new Point(1.0, 2.0);
Console.WriteLine(p1 == p2);   // true (value equality!)
Console.WriteLine(p1);         // Point { X = 1, Y = 2 }