Use of Inheritance in C#

07:39 0 Comments

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.

Ganesh

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.

0 comments:

Thanks for your Feedback !!!