Classes & OOP
Object-oriented programming
Introduction
In this lesson, you'll learn about classes & oop in C#. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with object-oriented programming.
C# has its own approach to object-oriented programming, which we'll explore step by step.
The C# Way
Let's see how C# handles this concept. Here's a typical example:
public abstract class Animal {
public string Name { get; } // auto-property
protected Animal(string name) { Name = name; }
public abstract string Speak();
}
public class Dog : Animal {
public Dog(string name) : base(name) {}
public override string Speak() =>
Name + " barks.";
}
var d = new Dog("Rex");
Console.WriteLine(d.Speak());
Console.WriteLine(d is Animal); // trueComparing to Python
Here's how you might have written similar code in Python:
class Animal:
def __init__(self, name: str):
self._name = name # convention: _ = "private"
@property
def name(self) -> str:
return self._name
def speak(self) -> str:
return f"{self._name} makes a sound."
class Dog(Animal):
def speak(self) -> str:
return f"{self.name} barks."
d = Dog("Rex")
print(d.speak())
print(isinstance(d, Animal))You may be used to different syntax or behavior.
C# uses : for inheritance; Python uses parentheses class Dog(Animal)
You may be used to different syntax or behavior.
C# auto-properties replace Python's @property decorator
You may be used to different syntax or behavior.
C# abstract forces override; Python has no abstract keyword by default
You may be used to different syntax or behavior.
C# override required; Python overrides silently
Step-by-Step Breakdown
1. Inheritance Syntax
C# uses colon for both inheritance and interface implementation. super() becomes base() in the constructor.
class Dog(Animal):
def __init__(self, name):
super().__init__(name)class Dog : Animal {
public Dog(string name) : base(name) {}
}2. Properties
C# auto-properties replace Python's @property. { get; } creates a read-only property; { get; set; } is read-write.
@property
def name(self): return self._namepublic string Name { get; private set; }3. Abstract Classes
C# abstract enforces that subclasses implement the method — Python uses NotImplementedError by convention.
def speak(self): raise NotImplementedErrorpublic abstract string Speak(); // must overrideCommon Mistakes
When coming from Python, developers often make these mistakes:
- C# uses : for inheritance; Python uses parentheses class Dog(Animal)
- C# auto-properties replace Python's @property decorator
- C# abstract forces override; Python has no abstract keyword by default
Key Takeaways
- class Dog(Animal) → class Dog : Animal
- super() → base()
- @property → auto-property { get; set; }
- abstract keyword enforces method implementation