Object-Oriented Programming Concepts in C#

Object-Oriented Programming is a programming pattern based on the concept of an object (name itself is explanatory). This object can contain properties and methods. In other words, an object can hold the data and perform operations on that data. C# is one of the famous and widely used Object-Oriented Programming languages. This tutorial is focused on the introduction and implementation of Object-Oriented Programming Concepts in C#.

Object-Oriented Programming Concepts in C#


Object-Oriented Programming Concepts in C#

The following are the main Object-Oriented Programming Concepts in C#

  • Abstraction: Represent the essential feature without representing the background details
  • Encapsulation: Wrapping up a data member and a method together into a single unit
  • Inheritance: Object reusability
  • Polymorphism: Many forms of a single object

Before going through in detail of these OOP concepts, let’s understand Class and Object first.

Class

Class is mandatory for representing data in any OOP language such as C#. A class is a core in C# or any Object-Oriented programming language.

A class is a blueprint of an object that contains variables for storing data and functions to perform operations on the data.

Use the “class” keyword flowed by class name to create a class.

Example:

class Student
{

} 

A class is only a logical representation of data hence it doesn’t occupy any memory space.

Object

Objects are the basic run-time entities of an object-oriented system. They may represent a person, a car or any item that the program must handle.

An object is an instance of a class

A class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, that is called an object.

Object-Oriented Programming Concepts in C#

When an object is created using the new operator, memory is allocated for the class in the heap, the object is called an instance and its starting address will be stored in the object in stack memory.

When an object is created without the new operator, the memory will not be allocated in the heap, that means instance will not be created and the object in the stack contains the value null.

When an object is null then members of the class cannot be accessed by using that object.
Example:

class Student
{

}
Student studentObject = new Student(); 

studentObject is the object of the Student class. We can access data members and methods of the Student class by using student objects.

Now, let’s go through OOP Concepts in C# in detail.

A. Abstraction:

Abstraction lets you focus on what the object does instead of how it does it.

  • Abstraction means represent the essential feature without representing the background details.
  • Abstraction is the process of hiding the working style of an object and showing the information of an object in an understandable manner.
  • Abstraction provides you a generalized view of your classes or objects by providing relevant information.

Other words – It is a process of identifying the critical behavior and data of an object and eliminating the irrelevant details

Abstraction is a common thing.

Example:
In college, you will provide your details like name, address, date of birth, grade, semester, percentage, etc.

In hospital, you will provide your details like name, address, date of birth, bold group, weight, height, etc.

You must observe that Name, address, and date of birth are common properties/data in this example hence you can create a class that consists of common data. Such classes are called Abstract class.

An abstract class is not complete, and it must be inherited by other classes.

Real-world Example of Abstraction

Suppose you have an object iPhone.

Suppose you have 2 mobile iPhones as in the following:

iPhone 5S(Features: Calling, Text, Touch Id) iPhone X(Features: Calling, Text, face recognition)
Object-Oriented Programming Concepts in C#
Abstract information (necessary and common information) for the object “iPhone” is that it makes a call to any number and can send Text/SMS.

So, for an iPhone object you will have the abstract class as in the following:
abstract class iPhone
{
    public void Call()
    { 
    }
    public void Text()
    {            
    }
} 
Following classes represents separate version of iPhone and will contain only unique data. These classes will implement iPhone class to get the common information.
public class iPhone5S : iPhone
    {
        public void TuchId()
        {
        }
    }

    public class iPhoneX : iPhone
    {
        public void FaceRecognition()
        {
        }
 }
 

Abstraction means putting all the variables and methods in a class that is necessary.

For example, Abstract class and abstract method.

B. Encapsulation

Wrapping up a data member and a method together into a single unit (in other words class) is called Encapsulation.

  • Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data associated with an object into that object.
  • Encapsulation means hiding the internal details of an object, in other words how an object does something.
  • Encapsulation prevents clients from seeing its inside view, where the behavior of the abstraction is implemented.
  • Encapsulation is a technique used to protect the information in an object from another object.
  • The Internal representation of an object is hidden from the view outside the object’s definition. Only the specified information can be accessed whereas the rest of the data implementation is hidden.
  • Hide the data for security such as making the variables private and expose the property to access the private data that will be public. So, once you access the property you’ll validate the data and set it.
  • Declare the ready only and write only properties to read and write data respectively.

Example:

public class Student
{
    private int _mark;
    private DateTime _dob;
    private string _classRoom;

    /// <summary>
    /// Mark - set private variable based on condition
    /// </summary>
    public int Mark
    {
        get
        {
            return _mark;
        }
        set
        {
            _mark = _mark > 0 ? _mark = value : _mark = 0;
        }
    }

    /// <summary>
    /// Date of Birth - Read only property
    /// </summary>
    public DateTime DOB
    {
        get
        {
            return _dob;
        }
    }

    /// <summary>
    /// Classroom - Write only property
    /// </summary>
    public string ClassRoom
    {
        set
        {
            _classRoom = value;
        }
    }
} 
Real-world Example of Encapsulation

Let’s take an example of Robot Vacuum Cleaner (Famous – iRobot Roomba) and its Manufacturers.

Suppose you are a Robot Vacuum Cleaner Manufacturer and you have designed and developed a Robot Vacuum Cleaner design (a class). Now by using machinery you are manufacturing Robot Vacuum Cleaner (objects) for selling, when you sell your Robot Vacuum Cleaner the user only learns how to use the Robot Vacuum Cleaner but not how the Robot Vacuum Cleaner works internally.

That means that you simply are creating the class with functions and by with objects (capsules) of which you are making available the functionality of your class by that object and without the interference in the original class.


C. Inheritance

Inheritance is a process of object reusability.

  • Inheritance is one of the most important pillars of Object-Oriented Programming in C#.
  • When a class includes a property of another class it is known as inheritance.
  • Other words inheritance means creating a new (derived) class from the existing (base) class.
  • Using Inheritance, a class can be act as a template for other classes.
  • In C#, a class that allows inheritance is called as Base Class and the class that inherits other class is called as Derived Class.
  • C# does not support multiple inheritance with classes, however, this can be achieved by using interfaces.

Example: A derived includes the properties of its base class iPhone.

public abstract class iPhone
{
    public iPhone()
    {
        Console.WriteLine("iPhone (base) class Constructor");
    }
    
    public void Print()
    {
        Console.WriteLine("I am an iPhone Class.");
    }
}

public class iPhoneX : iPhone
{
    public iPhoneX()
    {
        Console.WriteLine("iPhoneX (derived) class Constructor");
    }       
}

static void Main()
{
    iPhoneX obj = new iPhoneX();
    obj.Print();
} 
Output:
Object-Oriented Programming Concepts in C#

Real World Example of Inheritance

An example of Inheritance that exists in the real world is Shape class, which is a base class and its derived class can be  Circle, Square, etc.

Object-Oriented Programming Concepts in C#


D. Polymorphism

Many forms of a single object is called Polymorphism.

  • Polymorphism means one name, many forms.
  • One function behaves in different forms.
  • Polymorphism achieved by having multiple methods with the same name but different implementations.

Types of Polymorphism:

  1. Compile Time Polymorphism or Method Overloading.
  2. Run Time Polymorphism or Method Overriding
    Compile Time

1. Compile Time Polymorphism or Method Overloading: Create multiple methods with the same name but with different parameters is called as compile time polymorphism.

  • Compile time polymorphism is also called as early binding or static binding.

Example:

public class MathOperations
{
    public void Addition(int a, int b)
    {
        Console.WriteLine("Addition 1: a + b = {0}", a + b);
    }

    public void Addition(int a, int b, int c)
    {
        Console.WriteLine("Addition 2: a + b + c = {0}", a + b + c);
    }

    public void Substraction(int a, int b)
    {
        Console.WriteLine("Substraction 1: a - b = {0}", a - b);
    }

    public void Substraction(int a, int b, int c)
    {
        Console.WriteLine("Substraction 2: a - b - c = {0}", a - b - c);
    }
}

static void Main(string[] args)
{
    MathOperations operations = new MathOperations();
    operations.Addition(1, 2);
    operations.Addition(1, 2, 3);

    operations.Substraction(4, 2);
    operations.Substraction(8, 2, 3);

    Console.ReadLine();
} 
Output:
Object-Oriented Programming Concepts in C#


2. Run Time Polymorphism or Method Overriding:
Override a base class method in the derived class by creating a method with the same name and parameters called Run time polymorphism.

  • Overriding a base class method in the derived class by creating a similar function
  • This can be achieved by using override & virtual keywords along with the inheritance principle
  •  Run time polymorphism is also called late binding or dynamic binding

Example:

/// <summary>
/// Base Class Person0
/// </summary>
public class Person
{
    public virtual void GetInfo()
    {
        Console.WriteLine("This is a Person class");
    }
}

/// <summary>
/// Derived Class - Student
/// </summary>
public class Student : Person
{
    public override void GetInfo()
    {
        Console.WriteLine("This is a Student class");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Student student = new Student();
        student.GetInfo();

        Person person = new Person();
        person.GetInfo();

        Console.ReadLine();
    }
} 
Output:
Object-Oriented Programming Concepts in C#

Real-world Example of Polymorphism

Example 1:

A person behaves the son in a house while the person behaves an employee in an office.

Example 2:

Your mobile phone, one name but many forms:

  • As phone
  • As camera
  • As mp3 player
  • Wallet

Conclusion:

This is the basics of Object-Oriented Programming Concepts in C#. These are main pillars of any object oriented programming language.