Introduction

Roadmap

- Diving in OOP (Day 1): Polymorphism and Inheritance(Early Binding/Compile Time Polymorphism)
- Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
- Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time Polymorphism)
- Diving in OOP (Day 4): Polymorphism and Inheritance (All about Abstarct classes in C#)
- Diving in OOP (Day 5): All about access modifiers in C# (Public/Private/Protected/Internal/Sealed/Constants/Readonly Fields)
- Diving in OOP (Day 6): Understanding Enum in C# (A Practical Approach)
- Diving into OOP (Day 7): Properties in C# (A Practical Approach)
- Diving into OOP (Day 8): Indexers in C# (A Practical Approach)
- Diving into OOP (Day 9): Understanding Events in C# (An Insight)
Note: Each and every code snippet written in this article is tried and tested.
Inheritance in Action
InheritanceAndPolymorphism
. Add a class named ClassA
and a class named ClassB
, with the following code:ClassA:
class ClassA
{
}
ClassB:
class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(“ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(“ClassB Display2″);
}
}
ClassA
is empty and we added two methods in class ClassB
, i.e. Display1
and Display2
. We also have a variable x
declared and defined with a value 100
.Program.cs
class Program { static void Main(string[] args) {
ClassA a = new ClassA();
a.Display1();
}
}
'InheritanceAndPolymorphism.ClassA
‘ does not contain a definition for ‘Display1
‘ and no extension method ‘Display1
‘ accepting a first argument of type ‘InheritanceAndPolymorphism.ClassA
‘ could be found (are you missing a using
directive or an assembly reference?)Display1
method in ClassA
, nor can we access the same method usingClassA
instance because it is not derived from any such class like ClassB
that contains Display1
method. The class ClassA
does not contain any code or variable defined. An empty class does not throw any error as we are able to instantiate an object that looks like a (instance of ClassA
). The error comes about because the class ClassA
has no method called Display1
. However the class ClassB
has a method named Display1
. Guess how fun it could be if we are allowed to access all the code of classB
from ClassA
itself.ClassA
from ClassB
using : operator as code shown below:ClassA:
class ClassA:ClassB
{
}
ClassB:
class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(“ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(“ClassB Display2″);
}
}
Program.cs
class Program { static void Main(string[] args) { ClassA a = new ClassA(); a.Display1(); Console.ReadKey(); } }
Output
ClassB Display1
ClassA
can access the inherited public
methods of ClassB
. The error vanishes and the Display1
inClassB
gets invoked. If after the name of a class we specify : ClassB
i.e., the name of another class, a lot changes at once. ClassA
is now said to have been derived from ClassB
. What that means is all the code we wrote in ClassB
can now be accessed and used in ClassA
. It is if we actually wrote all the code that is contained in ClassB
in ClassA
. If we had created an instance that looks like that of ClassB
, everything that the instance could do, now an instance ofClassA
can also do. But we have not written a line of code in ClassA
. We are made to believe that ClassA
has one variable x
and two functions Display1
and Display2
as ClassB
contains these two functions. Therefore, we enterClassB
is the base class, ClassA
the derived class.
ClassA
also has a method of same name as of inClassB
. Let’s define a method Derive1
in ClassA
too, so our code for classA
becomes:class ClassA:ClassB { public void Display1() { System.Console.WriteLine("ClassA Display1"); } }
ClassB:
class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(“ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(“ClassB Display2″);
}
}
class Program { static void Main(string[] args) { ClassA a = new ClassA(); a.Display1(); Console.ReadKey(); } }
ClassA Display1
InheritanceAndPolymorphism.ClassA.Display1()
‘ hides inherited member ‘InheritanceAndPolymorphism.ClassB.Display1()
‘. Use the new
keyword if hiding was intended.ClassA
undoubtedly can contain Display1
method, that is already defined with the same name in ClassB
.a.Display1()
, C# first checks whether the class ClassA
has a method named Display1
. If it does not find it, it checks in the base class. Earlier Display1
method was only available in the base class ClassB
and hence got executed. Here, since it is there in ClassA
, it gets called from ClassA
and not ClassB
.Display1
method too with base keyword in derived class, i.e., by usingbase.Display1()
, so our ClassA
code will be:ClassA:
class ClassA:ClassB
{
public void Display1()
{
Console.WriteLine(“ClassA Display1″);
base.Display1();
}
}
ClassB:
class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(“ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(“ClassB Display2″);
}
}
Program.cs
class Program { static void Main(string[] args) { ClassA a = new ClassA(); a.Display1(); Console.ReadKey(); } }
Output
ClassA Display1 ClassB Display1
ClassA Display1
method is called and then ClassB Display1
method.ClassB
) Display1
first and then yours or vice versa. To achieve this, C# gives you a free keyword, called base
. The keyword base
can be used in any of the derived class. It means call the method off the base
class. Thus base.Display1
will call the methodDisplay1
fromClassB
the base classClassA
as defined earlier.
base
” can be used in derived class to call the base
class method.Display2
method from base
class, with an instance of derived class ClassA
?/// <summary> /// ClassB: acting as base class /// </summary> class ClassB { public int x = 100; public void Display1() { Console.WriteLine("ClassB Display1"); } public void Display2() { Console.WriteLine("ClassB Display2"); } }
/// <summary>
/// ClassA: acting as derived class
/// </summary>
class ClassA : ClassB
{
public void Display1()
{
Console.WriteLine(“ClassA Display1″);
base.Display2();
}
}
/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
class Program
{
static void Main(string[] args)
{
ClassA a = new ClassA();
a.Display1();
Console.ReadKey();
}
}
Output
base.Display1
was replaced by base.Display2
. In this particular scenario, method Display2
from the class ClassB
gets called. Base
is usually a very general purpose. It lets us access members of the base class from the derived class as explained earlier. We cannot use base
in ClassB
as ClassB
is not derived from any class as per our code. So it’s done that the base
keyword can only be used in derived classes?/// <summary> /// ClassB: acting as base class /// </summary> class ClassB { public int x = 100; public void Display1() { Console.WriteLine("ClassB Display1"); } }
/// <summary>
/// ClassA: acting as derived class
/// </summary>
class ClassA : ClassB
{
public void Display2()
{
Console.WriteLine(“ClassA Display2″);
}
}
/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
class Program
{
static void Main(string[] args)
{
ClassB b = new ClassB();
b.Display2();
Console.ReadKey();
}
}
Output
InheritanceAndPolymorphism.ClassB
‘ does not contain a definition for ‘Display2
‘ and no extension method ‘Display2
‘ accepting a first argument of type ‘InheritanceAndPolymorphism.ClassB
‘ could be found (are you missing a using
directive or an assembly reference?)ClassA
is derived from ClassB
, i.e., ClassB
is base class. Therefore, classClassA
can use all the members of class ClassB
. Inheritance does not have backwards compatibility, whatever membersClassA
contains do not permeate upwards toClassB
. When we tried to access Display2
method of classA
from the instance of class ClassB
, it cannot give it to class ClassB
and thus an error occurs.base
class .ClassC
is derived from class ClassB
, which in turn has been derived from class ClassA
, then ClassC
will inherit all the members declared in ClassB
and also of ClassA
. This is called transitive concept in inheritance. A derived class may inherit all the members of the base class but it cannot remove members off that base class. A derived class can however hide members of the base class by creating methods by the same name. The original member/method of the base class remains unmodified and unaffected by whatever happens in the derived class. It remains unchanged in the base class, i.e., simply not visible in the derived class.static
member that directly belongs to a class or an instance member that is accessed through instance of that class and belongs to that particular instance only. Instance member is accessible only through the object of the class and not directly by the class. The default member declared in the class are nonstatic
, we just have to make them static
by using static
keyword.Object
is the mother of all classes.:object
by itself to the class definition. Object
is the only class that is not derived from any other class. It is the ultimate base
class for all the classes.ClassA
is derived from ClassB
as in our case, but ClassB
is not derived from any class,public class ClassB { }
public class ClassA : ClassB
{
}
:object
to ClassB
, i.e., the code at compile time becomes:public class ClassB:object { }
public class ClassA : ClassB
{
}
ClassB
is the direct base class of ClassA
, so the classes of ClassA
are ClassB
and object.public class ClassW : System.ValueType { }
public class ClassX : System.Enum
{
}
public class ClassY : System.Delegate
{
}
public class ClassZ : System.Array
{
}
Errors
'InheritanceAndPolymorphism.ClassW' cannot derive from special class 'System.ValueType' 'InheritanceAndPolymorphism.ClassX' cannot derive from special class 'System.Enum' 'InheritanceAndPolymorphism.ClassY' cannot derive from special class 'System.Delegate' 'InheritanceAndPolymorphism.ClassZ' cannot derive from special class 'System.Array'

System.ValueType
, System.Enum
, System.Delegate
, System.Array
, etc.public class ClassW { }
public class ClassX
{
}
public class ClassY : ClassW, ClassX
{
}
ClassW
, ClassX
and ClassY
. ClassY
is derived from ClassW
and ClassX
. Now if we run the code, what would we get?InheritanceAndPolymorphism.ClassY
‘ cannot have multiple base classes: ‘InheritanceAndPolymorphism.ClassW
‘ and ‘ClassX
‘.class*
.public class ClassW:ClassY { }
public class ClassX:ClassW
{
}
public class ClassY : ClassX
{
}
ClassW
is derived from ClassY
, ClassX
is derived from ClassW
, and ClassY
in turn is derived from ClassX
. So no problem of multiple inheritance, our code should build successfully. Let’s compile the code. What do we get? Again a compile time error.InheritanceAndPolymorphism.ClassX
‘ and ‘InheritanceAndPolymorphism.ClassW
‘.
ClassX
is derived from ClassW
which was derived from ClassY
and ClassY
was again derived from ClassX
, which caused circular dependency in three classes, that is logically impossible.Equalizing the Instances/Objects
ClassB: public class ClassB { public int b = 100; }
ClassA:
public class ClassA
{
public int a = 100;
}
Program.cs
/// <summary> /// Program: used to execute the method. /// Contains Main method. /// </summary> public class Program { private static void Main(string[] args) { ClassB classB = new ClassB(); ClassA classA = new ClassA(); classA = classB; classB = classA; } }
Cannot implicitly convert type 'InheritanceAndPolymorphism.ClassB' to 'InheritanceAndPolymorphism.ClassA'
Cannot implicitly convert type ‘InheritanceAndPolymorphism.ClassA’ to ‘InheritanceAndPolymorphism.ClassB’
InheritanceAndPolymorphism
is the namespace that I used for my console application, so there is no need to be scared of that word, just ignore it.
classA
of ClassA
to classB
of ClassB
or vice versa. No matter the classes contain similar structure and their variables are initialized to similar integer value, even if we do.public class ClassB { public int a = 100; }
public class ClassA
{
public int a = 100;
}
int b
ofClassB
to int a
. In this case too, to equate an object is not allowed and not possible.ClassB
by declaring new
, we are creating two objects at one go, one that looks like ClassB
and the other that looks like object, i.e., derived from Object
class (i.e. ultimate base class). All classes in C# are finally derived from object. Since ClassA
is derived from ClassB
, when we declare newClassA
, we are creating 3 objects, one that looks like ClassB
, one that looks like ClassA
and finally that looks likeobject
class.public class ClassB { public int b = 100; }
public class ClassA:ClassB
{
public int a = 100;
}
/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
ClassA classA = new ClassA();
classA = classB;
classB = classA;
}
}
ClassA
from ClassB
, this is something we can do, we learned a lot about this in this article. Now compile the code, we get:InheritanceAndPolymorphism.ClassB
‘ to ‘InheritanceAndPolymorphism.ClassA
‘. An explicit conversion exists (are you missing a cast?)classA = classB
, classA
looks like ClassA
, ClassB
and object and as a looks like ClassB
, there is a match at ClassB.Result
? No error 
classB
and classA
have the same values, usingclassB
we can only access the members of ClassB
, even though had we used classA
we could access ClassA
also. We have devalued the potency of classB
. The error occurs at classA = classB
, because the class ClassB
is less/smaller than the class ClassA
. The class ClassA
has ClassB
and more. We cannot have a larger class on the right and a smaller class on the left. classB
only represents a ClassB
whereas classA
expects a ClassA
which is aClassA
andClassB
.public class ClassB { public int b = 100; }
public class ClassA:ClassB
{
public int a = 100;
}
/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
ClassA classA = new ClassA();
classB=classA;
classA = (ClassA)classB;
}
}
A()
is called a cast. Within the brackets, the name of the class is put. A cast basically proves to be a great leveller. When we intend to write classA = classB
, C# expects the right hand side of the equal to be a classA
, i.e., a ClassA
instance. But it finds classB
, i.e., a ClassB
instance. So when we apply the cast, we actually try to convert instance of ClassB
to instance of ClassA
. This approach satisfies the rules of C# on only equating similar objects type. Remember it is only for the duration of the line that classB
becomes a ClassA
and not a ClassB
.ClassB
as a base class to class ClassA
as in the following code, and try to typecast classA
toClassB
object.public class ClassB { public int b = 100; }
public class ClassA // Removed ClassB as base class
{
public int a = 100;
}
/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
ClassA classA = new ClassA();
classB = (ClassB)classA;
classA = (ClassA)classB;
}
}
Output
Cannot convert type 'InheritanceAndPolymorphism.ClassA' to 'InheritanceAndPolymorphism.ClassB' Cannot convert type 'InheritanceAndPolymorphism.ClassB' to 'InheritanceAndPolymorphism.ClassA'
InheritanceAndPolymorphism
’: Namespace I used in my application, so ignore that./// <summary> /// Program: used to execute the method. /// Contains Main method. /// </summary> public class Program { private static void Main(string[] args) { int integerA = 10; char characterB = 'A'; integerA = characterB; characterB = integerA; } }
Output
int
‘ to ‘char
‘. An explicit conversion exists (are you missing a cast?)int
to char
, but char
can be converted to int
.Conclusion

- No one can stop a derived class to have a method with the same name already declared in its base class.
- Derived classes get a first chance at execution, then the base class.
- A reserved keyword named “
base
” can be used in derived class to call thebase
class method. - Inheritance does not work backwards.
- Except constructors and destructors, a class inherits everything from its
base
class. - In inheritance in C#, custom classes cannot derive from special built in C# classes like
System.ValueType
,System.Enum
,System.Delegate
,System.Array
, etc. - A class can only be derived from one class in C#. C# does not support multiple inheritance by means of class.
- Circular dependency is not allowed in inheritance in C#.
ClassX
is derived fromClassW
which was derived fromClassY
andClassY
was again derived fromClassX
, which caused circular dependency in three classes, that is logically impossible. - We can only and only equate the dissimilar objects if they are derived from each other. We can equate an object of a base class to a derived class but not vice versa.
- We cannot implicitly convert an
int
tochar
, butchar
can be converted toint
.

Read more:
- C# and ASP.NET Questions (All in one)
- MVC Interview Questions
- C# and ASP.NET Interview Questions and Answers
- Web Services and Windows Services Interview Questions
Other Series
My other series of articles:
For more informative articles visit my Blog.
7 comments