OOPs Concepts in C# with Examples (2023)

Are you interested in learning about the fundamental concepts of Object-Oriented Programming (OOP) in C#? If so, you’re in the right place! This article will provide a comprehensive introduction to OOPs concepts in C#.

This post will go through object-oriented programming in C# and the four basic OOPs concepts.

C# OOP four basic OOPs concepts
C# OOP four basic OOPs concepts

What is object oriented programming?

Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects.” In OOP, an object is an instance of a class, which contains data (in the form of fields or properties) and code (in the form of methods) that operates on that data.

The key idea behind OOP is to represent real-world entities as objects and provide a way to model complex systems that are modular, reusable, and maintainable.

In OOP, a class is a blueprint or template that defines the properties and behaviors of an object. Each object is an instance of a class and can have its unique values for the properties defined in the class. We can use methods defined in the class to manipulate the object’s data or perform other operations.

OOP is used to structure a software program into simple, smaller, and reusable pieces of code (generally called classes), which are used to create individual instances of objects.

In Object-Oriented Programming (OOPs), the programs are organized around classes, objects, and data rather than action and logic.

Some of the key features of OOP include.

  • Encapsulation: The ability to hide data and implementation details within a class.
  • Abstraction: The ability to represent complex real-world entities using simplified models.
  • Inheritance: The ability to create new classes based on existing classes, inheriting their properties and behaviors.
  • Polymorphism: The ability to use a single interface to represent multiple related classes.

There are many object-oriented programming languages including C#, C++, Java, Python, and Ruby, etc.

Class and Object

In C#, everything revolves around classes and objects. A class is a blueprint that defines the properties and methods of an object. An object is an instance of a class.

For example, imagine you want to create a program that represents a car. You could create a Car class that defines properties such as color, model, and methods such as Start() and Stop(). You could then create an object of the Car class, such as myCar, with specific property values.

What is a class in C#?

class in C# is a user-defined data type that has data members and member functions. Class is a placeholder or container that allows us to declare variables of different data types and methods to perform some operation.

A class in C# is a template or prototype representing a collection of objects with similar properties and behaviors.

A class is a reference type stored in the heap memory.

Example of creating a class in C#

We can use the class keyword, to create a class followed by the class name and the body enclosed by a pair of curly braces {}.

// Creating class
public class Car
    {    
      // Data  members of a class
        public string brand = "Hyundai";
        public string modal = "Creta";
        public string color = "Red";
        public int topSpeed = 165;

        public void CarDetails()
        {
            Console.WriteLine($"Brand:{brand} Modal:{modal} Color: {color}: Speed:{topSpeed}");
        }
    }

What is an object in C#?

The object is an instance of a class that can be created using the new operator. An object in C# is used to access defined variables, properties, functions, and other class data members.

An object can’t be created until or unless a class is instantiated. The behavior of an object is defined by the actions that it performs.

Following are the characteristics of an object in C#.

  • State: Represents data (value) of an object. It also reflects the properties of an object.
  • Behavior: represents the methods or behavior (functionality) of an object, such as Drive, Brake, Speed, etc., of a car object.
  • Identity: It gives an object a unique name or ID and enables one object to interact with another.
  • The object ID is not visible to the external user. But, the compiler can use it internally to identify every object uniquely.

Example of creating an Object in C#

An object is created from a class using the new operator. As we have already created the class named “Car” in the above example, we can now use this to create objects.

To create an object of the Car class, we have to specify the class name, followed by the object name and use the new operator as below.

Create an object called carObj and use it to call the CarDetails method to print the car’s details.

using System;

namespace ClassExample
{
    // Car class
    public class Car
    {    
        // Data members
        public string brand = "Hyundai";
        public string modal = "Creta";
        public string color = "Red";
        public int topSpeed = 165;

        public void CarDetails()
        {
            Console.WriteLine($"Brand:{brand} Modal:{modal} Color: {color}: Speed:{topSpeed}");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Creating object of the Car class
            Car carObj = new Car();
            Console.WriteLine("****Print Car Details****");
            carObj.CarDetails();

        }
    }
}

Once we execute the above program, we will get the following result.

object in C# result
the output of the above C# program.

Four basics OOPs concepts:

There are four primary pillars or principles that define an Object-Oriented language.

01. Inheritance

Inheritance is the process of creating a new class from an existing class. The new class inherits all the properties and methods of the existing class and can also add new properties and methods.

Inheritance means a parent-child relationship where we can create a new class by using the existing class code.

  • C# Parent Class: In Inheritance, the class whose features are inherited is known as parent class(or a generalized class, superclass, or base class).
  • C# Child Class: The class that inherits the existing class is known as child class(or a specialized class, derived class, extended class, or subclass).

Example: Inheritance in C#

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("The animal makes a sound");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("The dog barks");
    }
}

The Animal class defines a virtual MakeSound() method in this example. The Dog class inherits from the Animal class and overrides the MakeSound() method with its own implementation.

Types of Inheritance in C#

The following are the different types of Inheritance:

  • Single Inheritance
  • Multilevel Inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Please check my earlier post for more information about Inheritance in C#

02. Encapsulation

Encapsulation is the process of hiding internal implementation details from the user and providing a public interface for interacting with the object. In C#, encapsulation is achieved through access modifiers such as public, private, protected, and internal.

  • Encapsulation is a technique to hide the properties and behaviors of an object to prevent the data from unwanted access by binding the code and data in a single unit called an object.
  • In C#, data inside an object can’t be accessed by any other object within a program, unless or until it is permitted to access.
  • if any object is maintaining or storing internal data safety is also called data hiding. We can achieve it by using the private access modifier.

So, whenever we want any property of an object( constants, variables, fields, method) to be revealed or exposed to others, we just have to set it as public property and when we don’t want it to be, we mark it as private.

Encapsulation means hiding and binding the data.

In order to achieve encapsulation, instance variables are kept private and can only be accessed through a class’s public properties or methods.

Example: Encapsulation in C#

public class Car
{
    private int speed;

    public void SetSpeed(int newSpeed)
    {
        if (newSpeed > 0)
        {
            speed = newSpeed;
        }
    }

    public int GetSpeed()
    {
        return speed;
    }
}

In this example, the Car class encapsulates the speed variable by making it private. The SetSpeed() and GetSpeed() methods provide a public interface for setting and retrieving the speed value.

Accessing the private variables by using public properties or methods of a class is a good example of encapsulation.

Please refer this link to read about the Differences between Abstraction and Encapsulation

03. Abstraction

Abstraction is the process of hiding complex implementation details while providing a simple interface for the user. In C#, abstraction is achieved through abstract classes and interfaces.
An abstract class is a class that cannot be instantiated and contains one or more abstract methods. An abstract method is a method that has no implementation and must be implemented by any class that inherits from the abstract class.

Example: Abstraction in C#

The following is an example of Abstraction.

using System;

namespace AbstractionExample
{

    // abstract class
    public abstract class Employee
    {
        public int EmpID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        // abstract method
        public abstract double CalculateSalary(int hoursWorked);
    }

    // derived class
    public class FullTimeEmployee : Employee
    { 
        //implementation of the abstract class method
        public override double CalculateSalary(int hoursWorked)
        {
            return hoursWorked * 60.00 + 3500;
        }
    }

    // derived class
    public class PartTimeEmployee : Employee
    {
        //implementation of the abstract class method
        public override double CalculateSalary(int hoursWorked)
        {
            return hoursWorked * 65.00;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Creating object of the derived classes by using base class reference variable.
            Employee employee = new FullTimeEmployee();
           Console.WriteLine($"Full Time Employee Salary: $ { employee.CalculateSalary(40)}");
            employee = new PartTimeEmployee();
           Console.WriteLine($"Part Time Employee Salary: $ { employee.CalculateSalary(40)}");

        }
    }
}

Once we run the above program, we will get the following result.

abstraction result-OOps
Result of the above abstraction program.

In the above example, we have created objects of the FullTimeEmployee and PartTimeEmployee classes, but we don’t create objects of the base class Employee. We only declare a variable of the abstract class called Employee to access the methods of the derived classes.

04. Polymorphism

Polymorphism means when a method acts differently under different conditions by taking different types of parameters. Polymorphism is the term used to describe the multiple behaviors of a single object.

Polymorphism is the process of using a single interface to represent multiple objects. In C#, polymorphism is achieved through the use of interfaces and method overloading.

Types of polymorphism in OOPs

Polymorphism in C# are mainly of two types:

  • Compile-time polymorphism (also known as Static polymorphism, Overloading, or Early binding)
  • Run time polymorphism (also known as Dynamic polymorphism, Overriding or late binding)

01.Static Polymorphism

The process of linking a method with an object during compile time is called early binding or static binding. C# provides the following two techniques to implement static polymorphism.

    • Method overloading
    • Operator overloading

a. Method overloading: Methods with the same name but different signatures. We can achieve method overloading by implementing multiple prototypes of the same method.

Let’s look into the following example of the method overloading for a clear understanding.

In the following example, a class “Calculator” has two methods with the same name “Add” but with different input parameters (the first method has two parameters and the second method has three input parameters).

using System;

namespace MethodOverloadingExample
{
    // class
    public class Calculator
    {
        // Overloaded method: Method with the same name but  different signatures
        public int Add(int a, int b)
        {
            return a + b;
        }
        public int Add(int a, int b, int c)
        {
            return a + b + c;
        }
    }

     class Program
    {
        static void Main(string[] args)
        {
            // Creating object of Calculator class.
            Calculator calculator = new Calculator();

            // Here compile will know which methods need to call at the compile-time based on 
           //the signature of the method.

            Console.WriteLine(calculator.Add(10, 20));
            Console.WriteLine(calculator.Add(10, 20,30));

        }
    }
}

//Output:
//30
//60

02. Dynamic Polymorphism in C#

Dynamic polymorphism or Run time polymorphism provides a mechanism to redefine or extend the functionality of a base class method in the derived class by using the override keyword.

Dynamic polymorphism gives us the provision to invoke all the identical or override methods of the derived class through the reference variable of the base class at the run time. To achieve dynamic polymorphism the base class method must be virtual or abstract and the derived class should have an override method.

Runtime polymorphism uses method overriding. In method overriding the base and child class can have a method with the same name and signature, but a child class can provide a different implementation than its parent class using the override keyword.

Polymorphism in C# is extensively used in implementing inheritance.

Let’s create a simple program to understand the method overriding in C#.

using System;

namespace MethodOverridingExample
{   // Base class
    public class Animal
    { // virtual method
        public virtual void Eat()
        {
            Console.WriteLine("Eating food.");
        }
    }
    // Derived class
    public class Cow : Animal
    {   //override method
        public override void Eat()
        {
            Console.WriteLine("Cow is eating grass");
        }
    }
    // Derived class
    public class Lion : Animal
    {   //override method
        public override void Eat()
        {
            Console.WriteLine("Lion is eating meat");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Calling object of cow class via base class reference variable.
            Animal animal = new Cow();
            animal.Eat();
            // Calling object of lion class via base class reference variable.
            animal = new Lion();
            animal.Eat();
        }
    }
}

//Output:
// Cow is eating grass
// Lion is eating meat

b. Operator Overloading in C#: The process of making an operator perform different behaviors in different class instances is known as operator overloading.

Please refer this link to learn more about the Polymorphism in C#

Summary:

This article covered the core OOPs concepts in C#, including abstraction, encapsulation, inheritance, and polymorphism. We also discussed the use of classes and objects in C# programming. You can create more robust and maintainable software applications by understanding these concepts. So start exploring the world of OOPs concepts in C# and take your programming skills to the next level!

Articles to check out:

Shekh Ali
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments