Override Methods in C#

In C#, when we override methods we have to keep remember some important points.

Assume there is a parent class called ClassA and it has a method called method(). 
If we are going to override that method in  a subclass ClassB, we have to use
virtual and override keywords properly in suitable places.


virtual should be used with method() in parent class and 
override should be used with method() in sub class. If we do not use these keywords properly
Overridden functionality  is not working properly. 

namespace BasicLangEx
{
    class ClassA
    {
        public virtual void method()
        {
            Console.WriteLine("Method A");
        }
    }
}

namespace BasicLangEx
{
    class ClassB : ClassA
    {
        public override void method()
        {
            Console.WriteLine("Method B");
        }   
    }
}
 

ClassA classb = new ClassB();
classb.method(); 

Output => Method B

Here, In compile time it checks whether method() is in the ClassA.
Because ClassA is the reference type of classb Object.
In runtime, it executes method() in ClassB according to the object type of classb object.

But, If you do not use virtual keyword with method() in super class and
override keyword with method() in subclass 
it gives output as Method A. 

Because, in run time it executes method() in ClassA according to the 
reference type of classb object as a normal method call not as a overridden method call. 

Comments

Popular posts from this blog

How to add standard and custom Metadata to PDF using iTextSharp

How to set and get Metadata to image using BitmapMetadata class in C#

How to generate direct line token to start a new conversation between your own client application and bot framework in Java