Understanding OOPs Concepts in .NET with Examples

Understanding OOPs Concepts in .NET with Examples

11 Jun 2024
Intermediate
2.4K Views
12 min read
Learn with an interactive course and practical hands-on labs

.NET Course

OOPs Concepts in .NET

OOP stands for Object Oriented Programming. It means a kind of programming where everything is represented by an object.  Understanding the OOP concepts can greatly enhance your coding skills and make your applications more robust and maintainable.

In this ASP.NET Core Tutorial, we'll dive deep into the essential OOP concepts, how they apply in ASP.NET, and why they're important. To learn more about various core concepts of ASP.NET, enroll in our ASP.NET Certification Training right now!
Read More: Top 50 ASP.NET Core Interview Questions and Answers for 2024

What is OOP?

Object Oriented Programming or OOP is a popular way of programming where objects are used to create the programs and applications. In OOP, an object can be anything like a car, person, or even a customer order. The ultimate goal of OOP is to elevate the flexibility and easy refactoring of the code by abstracting real-life entities.

What are Classes and Objects?

classes and objects

In OOP, a class is the equivalent of an architectural plan to build an object. An object is any empty framework characterized by some properties and behaviors. For example, consider the class Car. It is very probable that this car’s constituting parts could be things such as color or model; it would also include functions such as initiating movement or stopping movement respectively.

An object, however, is an instance of a class. Consider the Car class example: you can instantiate several car objects with different values for the attributes.

public class Car
{
    public string Color { get; set; }
    public string Model { get; set; }

    public void StartEngine()
    {
        Console.WriteLine("Engine started");
    }

    public void StopEngine()
    {
        Console.WriteLine("Engine stopped");
    }
}

// Creating an object
Car myCar = new Car();
myCar.Color = "Red";
myCar.Model = "Toyota";
myCar.StartEngine();

The 4 Basic Principles of OOP

Principles of OOP

1. Abstraction

Abstraction is about hiding the complex implementation details and showing only the necessary features of an object. It helps in reducing programming complexity and effort.  For example, when people are driving cars, they don't need to understand how the engine works. All they need to be familiar with are the pedals, steering wheel, and other control devices.
public abstract class Animal
{
    public abstract void MakeSound();
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof!");
    }
}

2. Encapsulation

Encapsulation in .NET
By restricting direct access to some parts of the object's components, the Object-oriented paradigm's main pillar of data protection technique is using encapsulation. Encapsulation in simple terms is wrapping data and functions within a single package or unit as provided by a class.
public class BankAccount
{
    private decimal balance;

    public void Deposit(decimal amount)
    {
        if (amount > 0)
        {
            balance += amount;
        }
    }

    public decimal GetBalance()
    {
        return balance;
    }
}

3. Inheritance

Inheritance in .NET
Inheritance provides functionality for one class to acquire properties and methods from another class so that code can be reused while maintaining a hierarchical structure of classes. For example, a Vehicle class can be the base class for Car and Bike classes.
public class Vehicle
{
    public string Brand { get; set; }
    public void Start()
    {
        Console.WriteLine("Vehicle started");
    }
}

public class Car : Vehicle
{
    public string Model { get; set; }
}

4. Polymorphism

Polymorphism in .NET
Polymorphism enables multiple classes derived from the same superclass to define their own unique behaviors and to provide for them accordingly. There are two types of polymorphism in OOP:
  1. Compile-time (method overloading)
  2. Runtime (method overriding)
public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Some sound");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof!");
    }
}
Read More: Salary Offered to ASP.NET Developers

The Significance of Composition over Inheritance in .NET

While inheritance is a powerful tool, it can lead to complicated hierarchies and tight coupling between classes. Composition, on the other hand, involves creating objects that contain other objects, allowing for more flexible and modular code. This principle is often summarized as "favor composition over inheritance."

public class Engine
{
    public void Start()
    {
        Console.WriteLine("Engine started");
    }
}

public class Car
{
    private Engine engine = new Engine();

    public void StartCar()
    {
        engine.Start();
        Console.WriteLine("Car started");
    }
}

Exception Handling in Object-Oriented .NET Programs

Building reliable applications is very important where Exception Handling helps. In .NET applications ensure robustness by using try-catch blocks to catch exceptions that may be thrown during program execution.
try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Handle exception
    Console.WriteLine(ex.Message);
}
finally
{
    // Cleanup code
}

Advanced Topics in OOP

1. Delegates

Delegates in .NET are those function pointers that are safe in a type-specific way. They help in the transfer of methods as arguments to other methods.
public delegate void Notify();  // delegate

public class ProcessBusinessLogic
{
    public event Notify ProcessCompleted; // event

    public void StartProcess()
    {
        Console.WriteLine("Process Started!");
        // Some processing logic
        OnProcessCompleted();
    }

    protected virtual void OnProcessCompleted()
    {
        ProcessCompleted?.Invoke();
    }
}

2. Events

Events help one class to let other classes know about exciting things happening. They are built on top of delegates.
public class Program
{
    public static void Main()
    {
        ProcessBusinessLogic bl = new ProcessBusinessLogic();
        bl.ProcessCompleted += Bl_ProcessCompleted; // register with an event
        bl.StartProcess();
    }

    public static void Bl_ProcessCompleted()
    {
        Console.WriteLine("Process Completed!");
    }
}

3. Generics

By using generics, we can define a class or method with a placeholder for the type of data it is supposed to hold or work with.
public class GenericList<T>
{
    private List<T> items = new List<T>();

    public void Add(T item)
    {
        items.Add(item);
    }

    public T Get(int index)
    {
        return items[index];
    }
}
Conclusion
This article aims to clarify what object-oriented programming is in ASP.NET and to enrich your programming skills using it. To understand more about ASP.NET Core, sign up for our ASP.NET Certification Course today!

FAQs

Object-Oriented Programming (OOP) in .NET is a programming concept in which everything is represented in the form of an object.

The key principles of OOP in .NET are:
  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

Classes act like a blueprint to create objects and an object is an instance of the class.

Encapsulation in .NET is an OOP principle where direct access is restricted for the data and methods of the object. It is implemented through access modifiers like private, protected, and public.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this