1

Let's assume there is such a class hierarchy:

 public class Parent
    {
        public virtual void Fun()
        {
            Console.WriteLine("In Parent");
        }
    }

public class FirstChild : Parent
{
    public override void Fun()
    {
        Console.WriteLine("In FirstChild");
    }
}

public class SecondChild : FirstChild
{
    public new void Fun()
    {
        Console.WriteLine("In SecondChild");
    }
}

Then we define a generic method which accepts argument derived from Parent:

public static void Test<T>(T entity) where T : Parent
        {
            entity.Fun();
        }

Finally in a client code we call it:

SecondChild child = new SecondChild();
Test(child); // Displays "In FirstChild"

The question is why the Fun method from FirstChild is called instead of Fun method defined in SecondChild?

Is there a casting involved behind the scenes?

Henry159
  • 11
  • 1
  • 2
    Note that you are using `new` instead of `override` for the `Fun` in `SecondChild`. Is that intentional? Change it to `override` and it should work as expected. – Sweeper Dec 19 '20 at 10:45
  • Does this answer your question? [Difference between new and override](https://stackoverflow.com/questions/1399127/difference-between-new-and-override) – Franz Gleichmann Dec 19 '20 at 10:46
  • `Test` can call any method defined in `Parent`, `SecondChild.Fun` is defined in `SecondChild`, not in `Parent` – Camilo Terevinto Dec 19 '20 at 10:46
  • Yes it is intentional in order to execute method from declared variable type and not from a runtime type. If I would skip generic approach the result would be as expected, but I am not sure why generics alter this behaviour. – Henry159 Dec 19 '20 at 10:49

0 Answers0