Use of Inheritance in C#

Why and when to use Inheritance? :

One of my friend once asked me a question on inheritance that i will explain below.
Consider a class below
Class Base
{
 int A;
 string str;
 public void test()
 {
  //Code...
 }
}
Class Derived: Base
{
 int k;
}

In above code Derived class inherits Base class with both variables being accessible in Derived class.
So the question is - what if i dont inherits Base class so i can access Base properties by creating object of Base in derived class. So why there is a need of inheritance?
Class Derived
{
 public void TestAgain()
 {
  Base b = new Base();
  b.test();
 }
}

Above class could use Base class members without inheritance. So why do we use inheritance?
I would explain it below.
So consider you have three Fruits in your application Banana,Mango and Orange. So there is a is-A relationship for three classes.
Banana is a Fruit, Mango is a Fruit and Orange is a Fruit so in this case you have common functionality for three classes that you will define  in one class name it Fruit that will be reused in all three classes if we use inheritance. This is one use of inheritance "Code Reusability". Also You have "Is a" relationship and you can use Inheritance in this situation.

Consider above class structure and there is code where you need to decide the object type on runtime whether type would be either of above fruit types.
For example a method accepts one type that would be either Banana,Mango or Orange

public void TestType(Banana b)
{
 // code......
}
public void TestType(Orange o)
{
 // code......
}
public void TestType(Mango m)
{
 // code......
}
In above situation we have defined three methods for all types but certainly thats not the correct and efficient code to write. so as we have Is a relationship we can write a following method that can accept any of parameter on runtime,

public void TestType(Fruit f)
{
 // code......
}

here Fruit is a base class for all three classes and any of the type is accepted. This is an example of runtime polymorphism
Hence this is one use of inhertiance.

And one more use of inheritance is that if there are changes to common functionalities then you can change it globally to reflect in derived classes and you edont need to change all derived classes.

So to summarize we can list out few points where inheritance can be useful.

-Your inheritance hierarchy represents an "is-a" relationship and not a "has-a" relationship.
-You can reuse code from the base classes.
-You need to apply the same class and methods to different data types.
-The class hierarchy is reasonably shallow, and other developers are not likely to add many more    levels.
-You want to make global changes to derived classes by changing a base class.

Static and Dynamic Polymorphism in c#

I hope you have gone through previous post to understand the basics of Object Oriented Concept in c#. If not, you can find it here fundamentals of OOP and Four Pillars of OOP.

This post is about one of the four pillars of OOP i.e. polymorphism in Object Oriented Programming that i am gonna explain via C#.
If you search the meaning of polymorphism  then it says, "the condition of occurring in several different forms" i.e. having same name but different behavior. If we consider our daily life event then we can give many example for polymorphism few of them are as

Example 1:
Person behaves as a SON in house, at the same time that person behaves like an EMPLOYEE in the office.
Example 2:
Your mobile phone, one name but many forms:

  • As phone
  • As camera
  • As mp3 player
  • As radio

So as per as programming is considered then any methods or properties have same name and performing different action we can say polymorphism is achieved. There are two types of polymorhism in c#
1.Static or compile time polymorphism
2.Dynamic or runtime polymorphism

Static or Compile time Polymorphism:

In this type as name suggest the decision of behavior is made at compile time that means compiler knows which method is going to get called during the compile time only. We achieve static polymorphism by using method overloading. Method overloading is nothing but class with more than one method with the same name but different parameters. Compiler checks the type and number of parameters passed on to the method and decides which method to call at compile time and it will give an error if there are no methods that match the method signature of the method that is called at compile time.
Example
In following example compiler already knows that Line 2 is going to call Add with two string parameters and Line 3 will call Add with two int parameters
class Program
    {
        public class Test
        {
            public void Add(string a1, string a2)
            {
                Console.WriteLine("Adding Strings :" + a1 + a2);
            }
            public void Add(int a1, int a2)
            {
                Console.WriteLine("Adding Integers :" +  a1 + a2);
            }
        }
        static void Main(string[] args)
        {
            Test obj = new Test();// Line 1
            obj.Add("Manish " , "Agrahari");//Line 2
            obj.Add(5, 10);//Line 3
        }
    }

Dynamic or Run time Polymorphism: 

Run time polymorhism can be achieved by using method overriding. In static type we saw two methods with same name but different signature can be declared within a class to achieve static binding but in method overriding or runtime polymorphism two methods i.e. in base class and derived class can have not only same name but also same parameters. By runtime polymorphism, we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding. 

Compiler would not be aware whether the method is available for overriding the functionality or not. So compiler would not give any error at compile time. At runtime, it will be decided which method to call and if there is no method at runtime, it will give an error.
Example

class Program

    {

        public class Base

        {
            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {
            public override void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBase;
            objBase = new Base();
            objBase.Show();//    Output ----> Show From Base Class.

            objBase = new Derived();
            objBase.Show();//Output--> Show From Derived Class.
        }
    }

Four Pillars of OOP

We all use OOP languages in daily life but we still find ourselves confused about few important concept of Object-Oriented Programming. So let me put few of those here to clear the air.
So the four pillars of OOP that are essential to achieve re-usability, managing complexity, information hiding etc are:


  • Encapsulation
  • Abstraction
  • Polymorphism
  • Inheritance

Encapsulation and Abstraction:



  • Many people are confused about these two topics. We all write the code but still don't know if we achieve abstraction and encapsulation in it. First thing we should understand is that these are general daily life concept we try to implement in our software (or many other things). We just need to correlate those with programming.

  • So lets take an example that we often see while reading these concept. Consider your cell phone. You use mobile phone in everyday life but you don't need to know the internal working of the phone such as how the circuits are connected and blah blah. You have very user friendly interface given to use them. For example you have buttons given on the phone and there are numbers. You just type them and internal controller will do its job to handle your request. So what is done here is that few of the things are there doing their job internally but you don't know its operation or rather you don't care. 



  • We have achieved Information hiding here by not showing internal working. 
We use the mobile interface to operate it and as a result we don't care about the internal things i.e. we have suppress complex things.



  • Encapsulation is a way to obtain "information hiding" so, you don't "need to know the internal working of the mobile phone to operate" with it. You have an interface to use the device without knowing implementation details.



  • Abstraction is a technique for managing complexity of computer systems. Abstraction captures only those details about an entity that are relevant to the current perspective. We achieve abstraction by using encapsulation i.e. information is hidden by Encapsulation.
So for above example internal phone circuits are hidden and we have interface to use the mobile and hence we have achieved abstraction here.

Encapsulation and Abstraction in program:

class A
    {
        private int a;
        public void print()
        {
            Console.WriteLine("Value of a = {0}", a);
        }
    }
    class B
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.print();                
        }
    }
  • In above program class A has a variable 'a' which is declared as private that means class B can not see the variable 'a'. If we want to use 'a' then we have to use class A's method print() which internally uses the same.
Hence we made 'a' hidden and have achieved abstraction by doing so.

Fundamentals of OOP - Classes and Objects




  • As the name suggest Object oriented programming is based on "objects" which is nothing but an instance of a class. Class contains fields often called attributes and blocks of code in the form of methods. So we can say object comprises of attributes and methods. In simple word, class is a blueprint for object and defines structure of object.
  • By creating classes we categorize the data we are representing and give these representations a context by associating them with features in the programming languages API. However a class is never used in the main program, it must first be instantiated as an object and the object is what we would use in our main program. In this sense a class is more like a blueprint, that describes the complex relationships between the data we are representing, like the blueprint of a house can describe how tall a wall will be or how far a window will be from the ceiling. If you can imagine a class to be like a blueprint then a software object is like a house made from that blueprint. For example, a class only describes the possible objects that can be instantiated from it, taking the blueprint analogy further we cannot live in a blueprint yet it has all the information we need to build a house which would be something that we use as a functional object. In other words we use the blueprint to build a house, this is just like instantiating an object from a class. The class only describes the possibilities of an object that can be instantiated from it and when we finally do instantiate an object from the class, it is the object that we use in our main program.
  • Real world example:

See the following image where we can see, the blueprint defines the structure of house which will help us construct the house. We can build as many houses(Objects) with different properties(fields) as we want just by changing the values.


Blueprint example

Note(image taken from lyndondaniels.com)