Look at given below steps:
- If method in the base and derived class are same and not made virtual in the base class and not being override in the derived then following case will occur :
- using System;
-
- public class Program
- {
- public static void Main()
- {
- Base objBase = new Base();
- objBase.Message();
-
- Derived objDerived = new Derived();
- objDerived.Message();
-
-
-
- objBase = new Derived();
- objBase.Message();
-
- }
- }
-
-
- public class Base
- {
- public void Message()
- {
- Console.WriteLine("I am Base");
- }
- }
-
- public class Derived : Base
- {
- public void Message()
- {
- Console.WriteLine("I am Derived");
- }
- }
- Output:
I am Base
I am Derived
I am Base
Executing Code URL: .NET Fiddle.
- If method in the base and derived class are same and made virtual in the base class and being override in the derived then following case will occur:
- using System;
- public class Program
- {
- public static void Main()
- {
- Base objBase = new Base();
- objBase.Message();
-
- Derived objDerived = new Derived();
- objDerived.Message();
-
-
-
- objBase = new Derived();
- objBase.Message();
-
- }
- }
-
- public class Base
- {
- public virtual void Message()
- {
- Console.WriteLine("I am Base");
- }
- }
-
- public class Derived : Base
- {
- public override void Message()
- {
- Console.WriteLine("I am Derived");
- }
- }
Executing Code URL: DotNetFiddle.
- If method in the base and derived class are same and not made virtual in the base class and not being override in the derived. Also, new keyword is being applied with the derived class method then following case happens:
- using System;
- public class Program
- {
- public static void Main()
- {
- Base objBase = new Base();
- objBase.Message();
-
- Derived objDerived = new Derived();
- objDerived.Message();
-
-
-
- objBase = new Derived();
- objBase.Message();
-
- }
- }
-
-
- public class Base
- {
- public void Message()
- {
- Console.WriteLine("I am Base");
- }
- }
-
- public class Derived : Base
- {
- public new void Message()
- {
- Console.WriteLine("I am Derived");
- }
- }
Output:
I am Base
I am Derived
I am Base
Executing Code URL: DotNetFiddle.