Dive into OOP principles like encapsulation, inheritance, polymorphism, and interface-driven design to build modular and maintainable C# applications.
In C#, classes are blueprints for creating objects. They encapsulate data (fields) and behavior (methods). Think of a class as a template that defines what properties and actions an object will have.
class
keyword.Program
class.To create an object, you use the instantiation process. This involves using the new
keyword followed by the class name and parentheses.
Person person = new Person();
A constructor is a special method that initializes an object when it's created. It has the same name as the class and no return type.
A parameterized constructor allows you to pass values when creating an object. This is useful for setting initial state.
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
Imagine building an application for a library. You might create a Book
class with properties like Title, Author, ISBN, and methods like Checkout() and Return(). Each book in the library is an instance of this class.
Inheritance is a fundamental concept in object-oriented programming that allows you to create a new class by extending an existing one. This promotes code reusability and creates a natural hierarchy between classes.
:class
keyword to derive a class from anotherPolymorphism means 'many forms' - the ability of an object to take on many shapes. In C#, this is achieved through method overriding and abstract classes.
// Base class
public class Animal {
public virtual void Speak() {
Console.WriteLine("Some noise");
}
}
// Derived class
public class Dog : Animal {
public override void Speak() {
Console.WriteLine("Woof!");
}
}
override
keyword to specify that a method is overriding one from the base classAn abstract class cannot be instantiated and is meant to be inherited. Abstract methods have no implementation in the base class and must be overridden by derived classes.
public abstract class Shape {
public abstract void Draw();
}
public class Circle : Shape {
public override void Draw() {
Console.WriteLine("Drawing a circle");
}
}
base
keyword when calling base class constructors in derived classesWelcome to the world of encapsulation in C#! This powerful concept allows you to create classes that are both secure and easy to use. By controlling access to class members, you can protect internal logic while exposing meaningful interfaces.
C# provides several access modifiers to control how class members can be accessed:
// Public member accessible everywhere
public int MaxSpeed = 200;
// Private member only within the class
private string secretKey = "12345";
The public access modifier allows unrestricted access to members from any part of the program. Use this for members that need to be widely available.
public class Car {
public void StartEngine() {
// Implementation
}
}
The private access modifier restricts access to the same class only. Use this for implementation details that shouldn't be exposed.
public class Car {
private string fuelType;
public void SetFuel(string type) {
fuelType = type;
}
}
The protected access modifier allows access within the same class and its derived classes. Use this for inheritance scenarios.
public class Vehicle {
protected int SpeedLimit;
}
public class Car : Vehicle {
public void SetSpeed(int speed) {
SpeedLimit = speed;
}
}
The internal access modifier restricts access to the same assembly only. Use this for members that need to be accessible throughout your application but not exposed externally.
internal class DatabaseConfig {
public string ConnectionString;
}
The protected internal access modifier combines protected and internal. Members can be accessed within the same assembly or by derived classes in any assembly.
public class BaseClass {
protected internal virtual void Execute() {
// Implementation
}
}
Welcome to Abstract Classes and Interfaces in C#! In this chapter, you'll learn how to create contracts for behavior using abstract classes and interfaces. These concepts are fundamental to writing scalable, maintainable code that adheres to the principles of object-oriented programming.
Both abstract classes and interfaces define contracts for behavior, but they serve different purposes. Let's explore their key differences:
abstract keyword
to declare methods, while interfaces use method signatures without implementation.// Abstract class example
public abstract class Animal {
public abstract void MakeSound();
}
// Interface example
public interface IMovable {
void Move();
}
Use abstract classes when you need to provide a °base implementation that can be shared by multiple derived classes§. This is particularly useful in scenarios where: - You want to share common code between related classes - You need to enforce a contract while providing default behavior
// Abstract class with base implementation
public abstract class Shape {
public abstract double CalculateArea();
public virtual void Print() {
Console.WriteLine("This is a shape.");
}
}
// Derived class
public class Circle : Shape {
public override double CalculateArea() {
return Math.PI * r * r;
}
}
Use interfaces when you need to define a °contract for behavior without any implementation details§. This is ideal in scenarios where: - You want to decouple classes from their implementations - You need multiple inheritance (since C# only supports single inheritance) - You're designing APIs or contracts that can be implemented by unrelated classes
// Interface example
public interface IPayable {
void Pay();
}
// Implementing the interface
public class Employee : IPayable {
public void Pay() {
Console.WriteLine("Paying employee salary.");
}
}
abstract methods
, while interfaces only declare method signatures.Interface-driven design (IDD) is a powerful approach that emphasizes defining contracts before implementation. Here's how to apply it effectively:
// Interface-driven design example
public interface IUserService {
Task<User> GetUserById(int id);
}
public class UserService : IUserService {
public async Task<User> GetUserById(int id) {
// Implementation details here
}
}
Question 1 of 22