Home Asp.net Top 10 OOPS Concepts In C# .NET With Examples

Top 10 OOPS Concepts In C# .NET With Examples

35
18

Object-Oriented OOPS Concepts in C#

Let me introduce you to OOPS Concepts in C#. OOP stands for Object Oriented Programming. It is a programming methodology that uses Objects to build a system or web applications using programming languages like C#, Vb.net, etc.

Here, Objects plays a very important role because it hides the implementation details and exposes only the needed functionalities and related stuff required to adopt it. We can access class properties and methods by creating a class object that I’ll explain below.

OOPS Concepts in C#, Features & Fundamentals

OOPS contains a list of elements that are very helpful to make object-oriented programming stronger. Here is the list of top 10 OOPS concepts in C# that we can implement in all major programming languages like c#, vb.net etc.

1] Class concepts in C#:

A class is a collection of objects and represents description of objects that share same attributes and actions. It contains characteristics of the objects such as objects attributes, actions or behaviors.

Here is the syntax and declaration example of Class:

public class Bike
{
//your code goes here..
}
2] Method:

Method is an object’s behavior.

For example, if you consider “Bike” as a class then its behavior is to get bike color, engine, mileage etc. Here is the example of Method:

public class Bike
{
//here is some properties of class Bike
public string color;
public string engine;
public int mileage;//here is some behavior/methods of class Bike
public string GetColor()
{
return “red”;
}
public int GetMileage()
{
return 65;
}
}

In above example GetColor() and GetMileage() are the methods considered as a object’s behavior.

3] Object Concepts in C#:

An object is a real-world entity that keeps together property states and behaviors.

For example, A “Bike” usually has common elements such as bike color, engine, mileage etc. In OOP terminology these would be called as a Class Properties or Attributes of a Bike object. Here is the example of Object:

public class Bike
{
//This is the class that contains all properties and behavior of an object//here is some properties of class Bike
public string color;
public string engine;
public int mileage;//here is some behavior of class Bike
public string GetColor()
{
return “red”;
}
public int GetMileage()
{
return 65;
}
}

Now we have a complete set of class with its properties and methods. So the question raise in mind is how we can access the class with its object? Right?

It is simple to create its object and access Bike class. You can create object of class via single line of code as shown below.

//It also considered as an “Instance of a Bike Class”
Bike objBike = new Bike();//Accessing Bike class methods
objBike.GetColor();
objBike.GetMileage();
4] Encapsulation Concepts in C#:

Encapsulation is the process of keeping or enclosing one or more items within a single physical or logical package. In object oriented programming methodology it prevents access to implementation details.

Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. Available access specifiers are public, private, protected, internal etc.

How we can achieve Encapsulation?
We can achieve Encapsulation by using private access modifier as shown in below example method.

private string GetEngineMakeFormula()
{
private string formula = “a*b”;
return formula;
}

Example – [Encapsulation]

public class Bike
{
public int mileage = 65;
public string color = “Black”;
private string formula = “a*b”;//Its public – so accessible outside class
public int GetMileage()
{
return mileage;
}//Its public – so accessible outside class
public string GetColor()
{
return color;
}

//Its private – so not accessible outside class
private string GetEngineMakeFormula()
{
return formula;
}
}

public class Program
{
public static void Main(string[] args)
{
Bike objBike = new Bike();
Console.WriteLine(“Bike mileage is : “ + objBike.GetMileage()); //accessible outside “Bike”
Console.WriteLine(“Bike color is : “ + objBike.GetColor()); //accessible outside “Bike”
//we can’t call this method as it is inaccessible outside “Bike”
//objBike.GetEngineMakeFormula(); //commented because we can’t access it
Console.Read();
}
}

So as you can see from above code that we hide GetEngineMakeFormula() method by using private access modifier because there is no need to give the make formula to users. So exposed only necessary methods for users to use it using public access modifier.

5] Abstraction Concepts in C#:

Abstraction is the process of providing only essential information to the outside real world and hiding overall background details to present an object. It relies on the separation of interface and implementation.

For example, we continue with “Bike” as an example, we have no access to the piston directly, we can use start button to run the piston. Just imagine if a bike manufacturer allows direct access to piston, it would be very difficult to control actions on the piston. That’s the reason why a bike provider separates its internal implementation from its external interface.

Example – [Abstraction]

public class Bike
{
public int mileage = 65;
public string color = “Black”;
private string formula = “a*b”;//Its public – so accessible outside class
public int GetMileage()
{
return mileage;
}//Its public – so accessible outside class
public string GetColor()
{
return color;
}

//Its private – so not accessible outside class
private string GetEngineMakeFormula()
{
return formula;
}

//Its public – so accessible outside class
public string DisplayMakeFormula()
{
//”GetEngineMakeFormula()” is private but accessible and limited to this class only
return GetEngineMakeFormula();
}
}

public class Program
{
public static void Main(string[] args)
{
Bike objBike = new Bike();
Console.WriteLine(“Bike mileage is : “ + objBike.GetMileage()); //accessible outside “Bike”
Console.WriteLine(“Bike color is : “ + objBike.GetColor()); //accessible outside “Bike”
//we can’t call this method as it is inaccessible outside “Bike”
//objBike.GetEngineMakeFormula(); //commented because we can’t access it
Console.WriteLine(“Bike color is : “ + objBike.DisplayMakeFormula()); //accessible outside
Console.Read();
}
}

As you can see from the above code that necessary methods and properties exposed using public access modifier and unnecessary methods and properties are hidden using private access modifier. This way we can implement abstraction or we can achieve abstraction in our code or web application.

Note: Abstraction and Encapsulation are related features in object oriented programming. Abstraction allows making relevant information visible and Encapsulation enables a programmer to implement the desired level of abstraction. That means the hidden part of class acts like Encapsulation and exposed part of class acts like Abstraction.

6] Information Hiding Concepts in C#:

Information Hiding concept restricts direct exposure of the data. Data is accessed indirectly using safe mechanism, methods in case of programming object. Follow the example given in Abstraction.

7] Inheritance:

Inheritance in OOP allows us to create a new class using an existing one meaning extending one class to another.

This concept can also be related to a real-world examples. Let’s take a Bike example again. A Bike manufacturer uses the same mechanism of the existing version of the bike while launching a new version with some additional added functionality. This allows the manufacturer to save their time and efforts both.

The main advantage of extending classes is that it provides a convenient way to reuse existing fully tested code in different contexts thereby saving lots of time with existing coding and its model style.

Example – [Inheritance]

public class Base
{
public Base()
{
Console.WriteLine(“Constructor of Base Class”);
}public void DisplayMessage()
{
Console.WriteLine(“Hello, how are you?”);
}
}public class Child : Base
{
public Child()
{
Console.WriteLine(“Constructor of Child class”);
}
}

public class Program
{
public static void Main(string[] args)
{
Child objChild = new Child();
//Child class don’t have DisplayMessage() method but we inherited from “Base” class
objChild.DisplayMessage();
Console.Read();
}
}

As you can see in the previous example code, We created an object of a Child class in Main() method and then called DisplayMessage() method of Base class. If you notice that the Child class doesn’t have DisplayMessage() method in it. So obviously it is inherited from the Base class. When you execute following code, result would be as show below:
Example Result

Constructor of Base Class
Constructor of Child class
Hello, how are you?

As per sample result, we can say that the “Base” class constructor will automatically be called before the “Child” class constructor.

Thus, here the conclusion is that “Base/Parent” classes are automatically instantiated before “Child/Derived” classes.

8] Polymorphism:

The word Polymorphism means having many forms. Generally, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

Let’s take Bike example, A Bike can be into two forms like cell start or kick start. We can, later on, decide which form or method we will use to start a bike to go for a drive (meaning at runtime).

There are two types of Polymorphism:

    • Compile-time polymorphism: In this type of polymorphism, the compiler identifies which polymorphism form it has to take and execute at compile time is called as compile time polymorphism or early binding. Examples of early binding are Method Overloading and Operator Overloading. The Method Overloading means more than one method having same name but different signatures (or parameters) in the same or different class.

      – Advantage: Execution will be fast because everything about the method is known to compiler during compilation.
      – Disadvantage: It has lack of flexibility.

Example – [Method Overloading]

public class Base
{
//1st: same method name, return type (object) but different parameter type (object)
public object Display(object a)
{
return (a);
}//2nd: same method name, return type (int) but different parameter type (int)
public int Display(int a)
{
return (a);
}
}public class Program
{
public static void Main(string[] args)
{
Base objBase = new Base();
int val = 7;

//here 2nd method will be called with type “int”
Console.WriteLine(objBase.Display(val));
Console.Read();
}
}

In above example, when you run the program, Display(int a) method will be called first because val is of type int at compile time. The assigned val is only refer to as a int at execution time.

Example Result

7
Note: While overloading methods, a rule to follow is the overloaded methods must differ either in number of arguments they take or the data type of at least one argument. We can also consider Method Overriding as a compile time polymorphism that is called directly by using derived objects.
    • Runtime polymorphism: In this type of polymorphism, compiler identifies which polymorphism form it has to take and execute at runtime but not at compile time is called as runtime polymorphism or late binding. Example of late binding is Method Overriding. The Method Overriding means having two methods with same name and same signature, one method in base class and other method in derived class. It must require changing the behavior of the base class methods in derived class to use its functionality differently.

      – Advantage: It has flexibility to adjust object types at runtime.
      – Disadvantage: Execution will be slow as compiler has to get the information about the method to execute at runtime.

We need to use either virtual methods or abstract method to allow the derived class to override a method of the base class.

Example – [Method Overriding by using virtual method]

public class Base
{
public virtual string BlogName()
{
return “AspnetO”;
}
}public class Child : Base
{
//same method name with same signature/parameters
public override string BlogName()
{
return “AspnetO – Quick Way To Learn Asp.net”;
}
}public class Program
{
public static void Main(string[] args)
{
Base objBase = new Child();
Console.WriteLine(objBase.BlogName());
Console.Read();
}
}

In above example, when you run the program, at compile time the type of objBase is Base but it will still call the child class’s override method because at the runtime, the type of the objBase object refers to is Child.

Example Result

AspnetO – Quick Way To Learn Asp.net

Example – [Method Overriding by using abstract method]

public abstract class Base
{
public abstract string BlogName();
}public class Child : Base
{
//same method name with same signature/parameters
public override string BlogName()
{
//It’s mandatory to implement abstract method in derived/child class
return “AspnetO – Quick Way To Learn Asp.net”;
}
}public class Program
{
public static void Main(string[] args)
{
Base objBase = new Child();
Console.WriteLine(objBase.BlogName());
Console.Read();
}
}

In above example, when you run the program, at compile time the type of objBase is Base but it will still call the child class’s override method because at the runtime, the type of the objBase object refers to is Child.

Example Result

AspnetO – Quick Way To Learn Asp.net
Note: Method Overloading and Method Overriding both are different OOP concepts and important also. Don’t be panic with their names it looks similar.
9] Constructors:

Constructors are special methods, used when instantiating a class. A constructor can never return anything, which is why you don’t have to define a return type for it.

A normal method is defined like this:

public string bike()
{
}

A simple constructor(without parameters) can be defined like this:

public bike()
{
}

And here is the example of parameterized constructor:

public class bike
{
private int mileage;
private string color;public bike()
{
//constructor without parameter
}public bike(int mil, string col)
{
//constructor with two parameters “mil” and “col”
mileage = mil;
color = col;
}

public void DisplayBikeData()
{
Console.WriteLine(“Bike’s Mileage is “ + mileage + ” and color is “ + color);
}
}

Key points to note about constructor are:

  • If no constructor defined then the CLR(Common Language Runtime) will provide an implicit constructor which is known as a Default Constructor.
  • Constructor doesn’t return a value.
  • Constructors can be overloaded.
  • A class can have any number of constructors and they vary with the number of arguments that are passed, which is they should have different parameters or signatures.
  • We don’t use references or pointers on constructors because their addresses cannot be taken.
  • Constructor doesn’t be declared with the virtual keyword.
10] Destructors Concepts in C#:

Since garbage cleanup is automatic system, framework will free the objects that are no longer in use BUT there may be times where we need to do some manual cleanup. In this case we can use Destructor, which is used to destroy the objects that we no longer want to use.

A destructor method called once an object is disposed, which can be used to clean up resources used by the object. Destructors don’t look very much like other methods.

Here is an example of a destructor for our Bike class:

public class Bike
{
public Bike()
{
//Constructor
}
~Bike()
{
//Destructor
}
}

Once the class object is instantiated, Constructor will be called and when object is collected by the garbage collector, Destructor method will be called.

If you have any questions related to this post, feel free to post comments below.

18 COMMENTS

  1. I love the fact that all the members of your classes are public. In a day and age when everyone is worried about privacy this is so refreshing. This is nothing short of a revolution in Object Oriented Programming Paradigm.
    Keep up the good work!

  2. Nice article.. But in the Constructor Example there is a mistake..
    should be :
    public bike(int mil, string col) {
    mileage = mil;
    color = col; }
    and not :
    … mil = mileage; col = color…

  3. Please correct sentence in late binding example
    *Example of early binding is Method Overriding*
    TO
    *Example of *{LATE} binding is Method Overriding*

  4. Your blog gave me a detailed insight into the topic. It was also very informative and practical. For such kind of quality and interesting stuff. I really enjoy reading your post and I collect some idea on oops concepts.
    Thank you

LEAVE A REPLY

Please enter your comment!
Please enter your name here
Captcha verification failed!
CAPTCHA user score failed. Please contact us!