2

I am trying to understand why it behaves as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstarctWithInterfcae
{  
public interface IBase
{
    void Display();
}

public abstract class Base : IBase
{        
    public void Display()
    {
        Console.WriteLine("Base Display");
    }
}


public class child1 : Base, IBase
{
    public new void Display()
    {
        Console.WriteLine("child1 Display");
    }
}

public class child2 : Base,IBase
{     
    public new void Display()
    {
        Console.WriteLine("child2 Display");
    }
}

class Program
{
    static void Main(string[] args)
    {
        IBase obj = new child1();
        obj.Display(); // writing child1 display
        IBase obj2 = new child2();
        obj.Display(); //Wrirting child1 dispaly
        Console.ReadLine();
    }
}
}

First Question :

In the above program as i am using new it should call base class method why it is calling Child 1 Display?

As per my understanding we have base class which already implemented the IBase so when we create instance for the child1 by referring to the interface it should call the base class method as it is inhering the base class and having the new key word.

If anybody gives explanation that would be appreciated

Chandra Mohan
  • 729
  • 2
  • 10
  • 29

2 Answers2

1

What you're seeing here is interface reimplementation. In the first case, the base class is the most-derived class to implement the interface, so it will bind the interface's method to it's implementation of the method. As that method isn't virtual, it can not be, and is not, overridden, so that is the method called when you use the interface on either the base or derived classes.

In the second example you re-implement the interface on the derived class (by adding it to the class's declaration). This re-binds the interface's methods using that type. Since it has a suitable method, its implementation is used whenever the interface is used to dispatch methods for the derived type.

Servy
  • 202,030
  • 26
  • 332
  • 449
-1

Scenario 1 is because you are using obj.Display() instead of obj2.Display()

Scenario 2 is because you are using general interface reference IBase, (IBase obj = new child2()) and C# will select for the least complex type to fit this of the actual object type because it assumes you want to operate on the 'least specific version' of the type since you are not being specific.

Edit: Noting the downvote, I'm assuming someone doesn't think this answer is complete enough;

If OP would like to see the output correctly for Error 2, they can instantiate the type as Child2 obj = new Child2();

C Bauer
  • 5,003
  • 4
  • 33
  • 62