All the programming languages
supporting Object oriented Programming will be supporting these three main
concepts:
1. Encapsulation
2. Inheritance
3. Polymorphism
Encapsulation in C#:
Encapsulation is process of keeping data and
methods together inside objects. In this way developer must define some methods
of object?s interaction. In C# , encapsulation is realized through the classes.
A Class can contain data structures and methods. Consider the following class.
public class Aperture
{
public Aperture()
{
}
protected double height;
protected double width;
protected double thickness;
public double GetVolume()
{
double volume = height*width*thickness;
if(volume<0)
return 0;
return volume;
}
}
In this example we encapsulate some data such as
height, width, thickness and method GetVolume. Other methods or objects can
interact with this object through methods that have public access modifier. It
must be done using ?.? operator.
Inheritance in C#:
In a few words, Inheritance is the process of
creation new classes from already existing classes. The inheritance feature
allows us to reuse some parts of code. So, now we have some derived class that
inherits base class?s members. Consider the following code snippet:
public class Door : Aperture
{
public Door() : base()
{
}
public bool isOutside = true;
}
As you see to inherit one class from another, we
need to write base class name after ?:? symbol. Next thing that was done in
code Door () ? constructor also inherits base class constructor. And at last we
add new private field. All members of Aperture class are also in Door class. We
can inherit all the members that has access modifier higher than protected.
Polymorphism in C#:
Polymorphism is possibility to change behavior
with objects depending of object?s data type. In C# polymorphism realizes
through the using of keyword virtual and override. Let look on the example of
code:
public virtual void Out()
{
Console.WriteLine("Aperture virtual method
called");
}
//This method is defined in Aperture class.
public override void Out()
{
Console.WriteLine("Door virtual method
called");
}
Now we need to re-define it in our derived Door
class. The usage of virtual methods can be clarified when we creating an
instance of derived class from the base class:
Aperture ap = new Door();
ap.Out();