In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier
Child Class Constructor executed
Write method in Base Class executed
Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans : Using Interfaces. We will talk about interfaces in our later article.
Common Interview Question: Are private class members inherited to the derived class?
If we want to call the parent class write () method, we would have to type cast the child object to Parent type and then call the write () method as shown in the code snippet below.
- It allows you to invoke methods of derived class through base class reference during runtime.
- It has the ability for classes to provide different implementations of methods that are called through the same name.
- Compile time polymorphism/Overloading
- Runtime polymorphism/Overriding
Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword.
Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.
Example:// Base class
public class BaseClass
public virtual void Method1()
Console.Write("Base Class Method");
// Derived class
public class DerivedClass : BaseClass
public override void Method1()
Console.Write("Derived Class Method");
// Using base and derived class
public class Sample
public void TestMethod()
// calling the overriden method
DerivedClass objDC = new DerivedClass();
// calling the baesd class method
BaseClass objBC = (BaseClass)objDC;
Derived Class Method Derived Class Method
- Constructors and destructors do not have return types nor can they return values.
- References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
- Constructors cannot be declared with the keyword virtual.
- Constructors and destructors cannot be declared const, or volatile.
- Unions cannot contain class objects that have constructors or destructors.
Example of Destructor