Classes & OOP
Object-oriented programming
Introduction
In this lesson, you'll learn about classes & oop in C#. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, 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 // : instead of extends
{
public Dog(string name) : base(name) {}
public override string Speak() =>
Name + " barks.";
}
var d = new Dog("Rex");
Console.WriteLine(d is Animal); // trueComparing to JavaScript
Here's how you might have written similar code in JavaScript:
class Animal {
#name;
constructor(name) { this.#name = name; }
get name() { return this.#name; }
speak() { return this.#name + " makes a sound."; }
}
class Dog extends Animal {
constructor(name) { super(name); }
speak() { return this.name + " barks."; }
}
const d = new Dog("Rex");
console.log(d instanceof Animal); // trueYou may be used to different syntax or behavior.
C# uses : for inheritance; JS uses extends
You may be used to different syntax or behavior.
C# auto-properties (get; set;) replace JS getter syntax
You may be used to different syntax or behavior.
C# override keyword required; JS overrides silently
You may be used to different syntax or behavior.
C# abstract keyword forces implementation in subclasses
Step-by-Step Breakdown
1. Inheritance Syntax
C# uses colon (:) for inheritance where JS uses extends. super() becomes base() in C#.
class Dog extends Animal { constructor() { super(); } }class Dog : Animal { public Dog() : base() {} }2. Properties
C# auto-properties are cleaner than JS getters. { get; set; } auto-generates backing field and accessor.
get name() { return this.#name; }public string Name { get; private set; }3. override Required
C# requires explicit override to replace a virtual/abstract method — prevents accidental hiding.
speak() { return "barks"; } // silently overridespublic override string Speak() => Name + " barks.";Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- C# uses : for inheritance; JS uses extends
- C# auto-properties (get; set;) replace JS getter syntax
- C# override keyword required; JS overrides silently
Key Takeaways
- extends → : (colon) in C#
- super() → base() in C#
- Auto-properties replace manual getter/setter
- override keyword required for method overriding