Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Learn OOP object oriented programming in C# Tutorial

OOP in C#.Net

Before we learn OOPS, we must be familiar with Class, Object, Property in C#, I am assuming you have already learned class

Now we learn 4 principles of OOP in C#

Abstraction in C# .net Example

Abstraction is one principle, It is used to display only necessary and essential features of an object to ouside the world.
Let's look at the abstract class code sample below
abstract class Car
{
public abstract string BrandType { get; set; }
public abstract string Mileage { get; set; }
public virtual void TestDrive(){}
}

Now we look at implementation
class Maruti : Car
{
public override string BrandType
{
get; set;
}

public override string Mileage
{
get; set;
}

// this is optional
public override void TestDrive()
{
base.TestDrive();
}
}

Encapsulation in C# .Net Example

Encapsulation means ability to hide data and behavior within object. Encapsulation enables a group of properties, methods and other members to be considered a single unit or object.

Now let's take a look at the example below
class CarBase
{
public CarBase()
{
}

public CarBase(string carkey)
{
Key = carkey;
Start();
}

public string Key { get; set; }

public void Start()
{
StartEngine();
}

private void StartEngine()
{
}
}

No if we want to start engine from outside different class, we cannot access the "StartEngine()" directly , but can start the engine by calling "Start()"; encapsulation example

Inheritance in .Net C# example
Inheritance is the ability to inherit members from base classs, when any class inherits the members of the base class is called the derived class.

let’s look at following example, we are inheriting above "CarBase" class
class SUV : CarBase
{
public SUV()
{
}
}
inheritance example
Note: In C#.NET supports only single inheritance, but we can multiple inheritance using Interace like example below
class SUV : CarBase, ICar, IDesign
{
public SUV()
{
}
}

Polymorphism in C#.Net Example
Polymorphism means multiple forms / shape, best way to express polymorphism is via an abstract base class (or interface).

Function Overloading is an example of static Polymorphism
Function Overriding is an example of dynamic Polymorphism
Let's see how we can implement Polymorphism in C#
abstract class CarBase
{

public void ModifyTVScreen()
{
}

public void ModifyTVScreen(string screenType)
{
}

public virtual void ModifyColor(string color)
{
}

}

Now we see how to override the above function
class SUV : CarBase
{
public override void ModifyColor(string color)
{
base.ModifyColor(color);
}

}

Look at function overloading below function overloading example

Comment
Name Email Website
Subscribe
 
OOP in C#
in C# Tutorials
Learn C# Online Tutorial



Learn C# .Net Programming Online
Group Training