Saturday, 18 August 2018

C#: Method Hiding

If sub class method has same signature as super class method, then sub class method hides the super class method. If you come from java background, it is quite different (To achieve run time polymorphism (or) method overriding, you need to use virtual keyword).

Program.cs
using System;

class A
{
    public void print()
    {
        Console.WriteLine("I am in A");
    }
}

class B : A
{
    public void print()
    {
        Console.WriteLine("I am in B");
    }
}

class Program
{
    static void Main(string[] args)
    {
        B b= new B();
        b.print();
    }
}

Output
I am in B


Following example is for the guys, who come from Java background.

Which method is called, when my sub class instance points to super class variable?
A a= new B();
a.print();    // Calls super class print method

If you are from Java, you definitely say, sub class method is called (Refer method overriding). But in C#, super class print method is called. To achieve run time polymorphism, you need to use the ‘virtual’ keyword. I will explain this in later post.

Program.cs
using System;

class A
{
    public void print()
    {
        Console.WriteLine("I am in A");
    }
}

class B : A
{
    public void print()
    {
        Console.WriteLine("I am in B");
    }
}

class Program
{
    static void Main(string[] args)
    {
        A a= new B();
        a.print();
    }
}

Output
I am in A






Previous                                                 Next                                                 Home

No comments:

Post a Comment