DEV Community

Deepangshi S.
Deepangshi S.

Posted on • Updated on

OOP Concepts C# : Mastering

🚀 Object Oriented Programming in C#(i.e great topic): OOP is a powerful paradigm that allows you to organize and structure your code in a more modular and reusable way.

Encapsulation- Encapsulation is about bundling the data (variables) and methods that operate on the data into a single unit or class. It also restricts direct access to some of an object's components, which can prevent the accidental modification of data. In C#, this is implemented using access modifiers like public, private, protected, and internal.

public class Account
{
    private double balance;  // Private variable, encapsulated

    public double GetBalance()
    {
        return balance;
    }

    public void Deposit(double amount)
    {
        if (amount > 0)
        {
            balance += amount;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Inheritance- Inheritance allows you to create new classes based on existing classes. The new class(derived class) inherits the properties and methods of the existing class (base class). It helps in code reuse and creating a hierarchy of classes. In C#, this is denoted using the : symbol.

public class BaseAccount
{
    public double balance;
}

public class SavingsAccount : BaseAccount
{
    public double interestRate;

    public void ApplyInterest()
    {
        balance += balance * interestRate;
    }
}
Enter fullscreen mode Exit fullscreen mode

Polymorphism- Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables us to use the same method name and signature to perform different actions based on the specific object being used. This can be achieved both statically at compile-time and dynamically at runtime. It's a powerful concept that adds flexibility and extensibility to our code.

Method overloading allows us to have multiple methods with the same name but different parameters within a class.

Method overriding occurs when a subclass provides its own implementation of method i.e already defined in its superclass.

In this example uses a base class Employee and two derived classes Manager and Intern to show how each can have a different implementation of the CalculateBonus method.

using System;

// Base class
public class Employee
{
    public string Name { get; set; }
    public decimal Salary { get; set; }

    public Employee(string name, decimal salary)
    {
        Name = name;
        Salary = salary;
    }

    // Virtual method
    public virtual decimal CalculateBonus()
    {
        return Salary * 0.05m; // Standard 5% bonus for regular employees
    }

    public void Display()
    {
        Console.WriteLine($"{Name} earns a bonus of {CalculateBonus():C}");
    }
}

// Derived class for Managers
public class Manager : Employee
{
    public Manager(string name, decimal salary) : base(name, salary) { }

    public override decimal CalculateBonus()
    {
        return Salary * 0.10m; // 10% bonus for managers
    }
}

// Derived class for Interns
public class Intern : Employee
{
    public Intern(string name, decimal salary) : base(name, salary) { }

    public override decimal CalculateBonus()
    {
        return Salary * 0.01m; // 1% bonus for interns
    }
}

public class Program
{
    public static void Main()
    {
        Employee alice = new Employee("Alice", 50000);
        Manager bob = new Manager("Bob", 100000);
        Intern charlie = new Intern("Charlie", 20000);

        alice.Display();
        bob.Display();
        charlie.Display();
    }
}

Enter fullscreen mode Exit fullscreen mode

Abstraction- Abstraction means hiding the complex reality while exposing only the necessary parts. It is generally implemented using abstract classes and interfaces.

public abstract class Shape
{
    public abstract double Area();
}

public class Circle : Shape
{
    private double radius;

    public Circle(double radius)
    {
        this.radius = radius;
    }

    public override double Area()
    {
        return Math.PI * radius * radius;
    }
}
Enter fullscreen mode Exit fullscreen mode

There are additional concepts and features in object-oriented programming that are crucial for designing robust and maintainable systems. Here are some key additional concepts:

Classes are the building blocks of object-oriented programming. The define the blueprint for creating objects. You can define properties (attributes) and methods (behaviors) within a class.

Class- A class like Book serves as a blueprint for creating book objects. It includes characteristics (fields or properties) common to all books, such as title, author, and ISBN, as well as behaviors (methods) that a book might exhibit, like displaying its details.

public class Book
{
    // Properties
    public string Title { get; set; }
    public string Author { get; set; }
    public string ISBN { get; set; }

    // Constructor
    public Book(string title, string author, string isbn)
    {
        Title = title;
        Author = author;
        ISBN = isbn;
    }

    // Method
    public void Display()
    {
        Console.WriteLine($"Title: {Title}, Author: {Author}, ISBN: {ISBN}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Objects are instances of a class. They represent specific instances of the class and can store data in their properties and perform actions using their methods.

An object is an instance of a class. When you instantiate a Book, you are creating a specific book with actual values for title, author, and ISBN.

public class Program
{
    public static void Main()
    {
        // Creating an object of Book
        Book myFavoriteBook = new Book("1984", "George Orwell", "978-0451524935");
        myFavoriteBook.Display();

        // Creating another book object
        Book anotherBook = new Book("Brave New World", "Aldous Huxley", "978-0060850524");
        anotherBook.Display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Constructors- Constructors are special methods in a class that are called when an object is instantiated. They are typically used to initialize an object's properties or to perform setup tasks. Constructors can be overloaded to provide multiple ways of initializing objects.

- Default Constructor: A default constructor is one that takes no arguments. It is automatically provided by the compiler if no constructors are explicitly defined.

public class Employee
{
    public string Name;
    public int Age;

    // Default constructor
    public Employee()
    {
        Name = "Unknown";
        Age = 0;
    }
}
Enter fullscreen mode Exit fullscreen mode

Usage:

 Employee employee1 = new Employee();
Console.WriteLine($"Name: {employee1.Name}, Age: {employee1.Age}");
Enter fullscreen mode Exit fullscreen mode

- Parameterized Constructor: A parameterized constructor allows passing arguments to initialize your object's properties with specific values at the time of object creation.

public class Employee
{
    public string Name;
    public int Age;

    // Parameterized constructor
    public Employee(string name, int age)
    {
        Name = name;
        Age = age;
    }
}
Enter fullscreen mode Exit fullscreen mode

Usage:

Employee employee2 = new Employee("John Doe", 30);
Console.WriteLine($"Name: {employee2.Name}, Age: {employee2.Age}");

Enter fullscreen mode Exit fullscreen mode

- Static Constructor: A static constructor is used to initialize static members of the class. It is called automatically before the first instance is created or any static members are referenced.

public class DatabaseSettings
{
    public static string DatabaseName;
    public static int Timeout;

    // Static constructor
    static DatabaseSettings()
    {
        DatabaseName = "MyDatabase";
        Timeout = 30;
    }
}
Enter fullscreen mode Exit fullscreen mode

Usage

// Accessing a static property also triggers the static constructor
Console.WriteLine($"Database: {DatabaseSettings.DatabaseName}, Timeout: {DatabaseSettings.Timeout}");
Enter fullscreen mode Exit fullscreen mode

Advanced Scenario: Combining Constructors

public class Person
{
    public string FirstName;
    public string LastName;
    public int Age;

    // Default constructor
    public Person()
    {
        FirstName = "First";
        LastName = "Last";
    }

    // Parameterized constructor
    public Person(string firstName, string lastName, int age) : this() // Calls default constructor first
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }
}

Enter fullscreen mode Exit fullscreen mode

Usage

Person person1 = new Person();
Person person2 = new Person("John", "Doe", 28);
Console.WriteLine($"Name: {person1.FirstName} {person1.LastName}");
Console.WriteLine($"Name: {person2.FirstName} {person2.LastName}, Age: {person2.Age}");

Enter fullscreen mode Exit fullscreen mode

Top comments (0)