Polymorphism – C# Programming interview Questions

C# programming interview questions and answers on polymorphism with explanation asked in technical job interview for freshers and experienced.

Topic –  Polymorphism – Method Overloading, Method Overriding and Operator Overloading, virtual.


Q – If we call the below statements in main (), what is the wings’ colour of Parrot? Give reason.

Bird b = new Parrot();
b.wings();
In case of unknown colour, complete the source code of classes to get correct colour of Parrot’s wings.

//Birds classes
class Bird
{
    public void legs() { Console.WriteLine("legs:2"); }   
    public void wings(){Console.WriteLine("colour:unknown"); }
}
class Parrot : Bird
{
    public void wings() { Console.WriteLine("colour:Green"); }
}

Answer:

Parrot wings’ colour will be unknown as below statement will call wings() method of the base class i.e. Bird. As base class wings() method is not virtual and not overriden in derived class to get its own implementation.

Bird b = new Parrot();

b.wings();

To get the correct parrot wings’ colour we need to declare wings() method as virtual and have to override it in derived that is Parrot class. Example and source code below –

//Birds classes
class Bird
{
    public void legs() { Console.WriteLine("legs:2"); }   
    public virtual void wings(){Console.WriteLine("colour:unknown"); }
}
class Parrot : Bird
{
    public override void wings() { Console.WriteLine("colour:Green"); }
}

//------------TEST-----------
  class Program
    {
        static void Main(string[] args)
        {             
            Bird b = new Parrot();
            b.wings();
        }
    }


Q- What is output of the below program? What is significance of applying “new” keyword before function name e.g. public new void display ()?

class Base
{
    public void print()
    {
        Console.WriteLine("Base: Print");
    }
    public void display()
    {
        Console.WriteLine("Base: display");
    }
}

class Derived : Base
{
    public void print()
    {
        Console.WriteLine("Derived: Print");
    }
    public new void display()
    {
        Console.WriteLine("Derived: display");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Base b = new Derived();//base class reference with child object
        b.print();
        b.display();
    }
}

Answer: Output will be

Base: Print

Base: display

Explanation: In both cases, base class methods will be called. This is method hiding feature in c# programming i.e. if base class and derived class both contain methods with same name and if we use base reference with child object then base class methods will be always called.

The new keyword in function public new void display() just suppress the warning. If we don’t use new keyword there is no harm and program will be successful with a warning.

NOTES: Using a “new” keyword is a good practice if method hiding is intentional in C# programming. It shows a programmer that method hiding is being used here intentionally ,so, he doesn’t have to worry about applying other features e.g. method overriding or any mistake has happened at the time of writing this class in software projects.


Q – What is output of below program? Is using virtual keyword in method print OK?

class Base
{
    public virtual void print()
    {
        Console.WriteLine("Base: Print");
    }  
}
class Derived : Base
{   
    public new void print()
    {
        Console.WriteLine("Derived: display");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Base b = new Derived();//base class reference with child object
        b.print();        
    }
}

Answer: Output will be

Base: Print

In derived class method hiding is programmed and method hiding has nothing to do with virtual method. It doesn’t matter if base class method is virtual or non-virtual, method hiding will work.

So, for method hiding virtual keyword is not required in the base class method.

However, we may keep print() method in base class as a virtual if another classes want to derived from base class and implement new behavior for print() method.


Q- What is output of below program? Explain statements in main program source code?

class X
{
    public void func()
    {
        Console.WriteLine("X:func()");
    }
}

class Y : X
{
    public void abc()
    {
        Console.WriteLine("Y:abc()");
    }
}


class Program
{
    static void Main(string[] args)
    {
        X x = new Y();
        x.abc();
    }
}

Answer

Output : Compiler error.
Explanation:We will get compiler error at statement x.abc(); as we are assigning derived class object to base class reference(X x = new Y();) and making a call of derived class’s method with base class reference(x.abc();).
Since, object x, the base class type only can understand the functions of its type( only functions of base class X)and function abc() is not available in base class.So, Base class object don’t understand derived class function even though we assign derived class object to a base reference.
If intention is to call derived function that is not available in base class and we want to use base reference with derived object, we need downcasting from base type to derived type and then call derived class function e.g. below program is correct with no compiler error.

class Program
{
    static void Main(string[] args)
    {
        X x = new Y();
        Y y = (Y)x;//downcast( base class type to derived type)
        y.abc();
    }
}


Q- Can you find any issue in execute() method? If yes, correct it.

class Animal
{
    public void run()
    {
        Console.WriteLine("Animal:run()");
    }
}

class Cat : Animal
{
    public void sound()
    {
        Console.WriteLine("Cat:meow()");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Animal a = new Cat();
        execute(a);

    }
    public static void execute(Animal a)
    {
        Cat c = (Cat)a;
        c.sound();
    }
}

Answer: In execute (Animal a)method, run time downcasting is happening at statement Cat c = (Cat)a; i.e. base class type to derived class type.

There is no error in the source code but there could be a potential bug or crash.
For example, lets say, at some later point of time we introduced a new class Dog as below

class Dog : Animal
{
    public void sound()
    {
        Console.WriteLine("Dog:bark()");
    }
}

Now, in main if we make a call of execute(Animal a) method with Dog object as a parameter e.g.

    static void Main(string[] args)
    {
        Animal a = new Dog();
        execute(a);

    }

then software programs will crash stating InvalidCastException: unable to cast object of type ‘Dog’ to type ‘Cat’.

So, as a solution we can write like this

public static void execute(Animal obj)
    {
        if (obj is Cat)
        {
            Cat c = (Cat)obj;
            c.sound();            
        }
    }

In-case we introduced a new class Dog, we can write the execute method as below

public static void execute(Animal obj)
    {
        if (obj is Cat)
        {
            Cat c = (Cat)obj;
            c.sound();            
        }else if(obj is Dog){
            Dog d = (Dog)obj;
            d.sound();
        }
    }


Q – In below program, which Syntax is better for typecasting objects and why?

Syntax-1:
Derived _derived=(Derived)_base;  
Syntax-2:
Derived _derived = _base as Derived;
class Base { }
class Derived :Base{ }

class Program
{
    static void Main(string[] args)
    {
        //Create object of derived class into base reference.
        Base _base = new Derived();
        
        //Conver base reference object into derived object
        //Which is better type cast from base to derived class

        Derived _derived=(Derived)_base; //Syntax 1

        //or        
        Derived _derived = _base as Derived;//Syntax-2
    }
}

Answer: Better is Syntax -2 i.e. Derived _derived = _base as Derived;, as on typecasting from base to derived type,if type casting fails, null will be returned and no exception.

But, in Syntax-1 Derived _derived=(Derived)_base; if typecasting fails, it will cause exception and software program will crash.

NOTES: Example for typecast failure.

In below program in DisplayShape(Shape s) method, if Shape object s is other than that of Circle, for example Rectangle then program will crash.

class Shape{}
class Circle : Shape{}
class Rectangle : Shape { }

//Test IS : if object is circle, "Circle" will be displayed or 
// "Not a Circle"
class Program
{
    static void Main(string[] args)
    {
        Shape sc = new Circle();
        DisplayShape(sc);

        Shape sr = new Rectangle();
        DisplayShape(sr);
        

    }
    
public static void DisplayShape(Shape s)
    {
        // if shape object s is other than 
        //Circle e.g. Rectangle, type cast will fail 
        //resulting Exception and
        //program Crash.
        Circle c = (Circle)s;
        
    }
}


Q – In below program, at the place of question mark before class B function signature, what specifier should be applied, “virtual”, “virtual override” or “override”?

class A
{
    public virtual void f() { Console.WriteLine("f(): class A"); }
}
class B : A
{
    public ? void f() { Console.WriteLine("f(): class B"); }
}
class C : B
{
    public override void f() { Console.WriteLine("f(): class C"); }
}

Answer: “override”.
Explanation: In this polymorphic example, we need to put virtual keyword before function declaration of base class only. And all the child classes will override this function using “override” keyword only.

Complete Example with Source Code :

class A
{
    public virtual void f() { Console.WriteLine("f(): class A"); }
}
class B : A
{
    public override void f() { Console.WriteLine("f(): class B"); }
}
class C : B
{
    public override void f() { Console.WriteLine("f(): class C"); }
}


class Program
{
    static void Main(string[] args)
    {
        A o1 = new B();
        o1.f();

        A o2 = new C();
        o2.f();
    }
}

Output:
f(): class B
f(): class C


Q – What is issue with below program?

class Shape
{
    private virtual void draw() { Console.WriteLine("draw(): Shape"); }
}
class Circle:Shape
{
    public override void draw() { Console.WriteLine("draw(): Circle"); }    
}
class Program
{
    static void Main(string[] args)
    {
        Shape s = new Circle();
    }
}

Answer:Issue is that a virtual method cannot be private in base class Shape.So, it should be public.

NOTES:

Making a method virtual means, we want some child classes to implement their own behaviour by overriding this method. Some child class may use base class method etc.  Means, it should be accessible from outside of the class. So, virtual method should be public. Private methods are not accessible from outside of the class.

Example with comments:

//Base class

class Shape
{
    //virtual method should be public
    public virtual void draw() { Console.WriteLine("draw(): Shape"); }
}
class Circle:Shape
{
    //override draw() method and implement it 
    public override void draw() { Console.WriteLine("draw(): Circle"); }    
}
class Square: Shape
{   
    //use base class draw() method
   
}

static void Main(string[] args)
    {
         
        Shape sq = new Square();
        sq.draw();//call base class draw() method.

        Shape cir = new Circle();
        cir.draw();//call Circle class draw() method.

    }


Related Posts