0

Why does c# not call the new Method1 from DerivedClass and instead calls Method1 on the BaseClass?

using System;
                    
class BaseClass  
{  
    public void Method1()  
    {  
        Console.WriteLine("Base - Method1");  
    }  
}  
  
class DerivedClass : BaseClass  
{  
    public new void Method1()  
    {  
        Console.WriteLine("Derived - Method1");  
    }  
}  

class GenericClass<T> where T: BaseClass {
    public void CallMethod(T instT) {
        instT.Method1();
    }
}

public class Program
{
    public static void Main()
    {
        DerivedClass dc = new DerivedClass();
        GenericClass<DerivedClass> gc = new GenericClass<DerivedClass>();
        gc.CallMethod(dc);
        dc.Method1();
    }
}
# outputs
Base - Method1
Derived - Method1

EDIT: The specification at 8.5 say this. It seems related.

The rules for member lookup on type parameters depend on the constraints, if any, applied to the type parameter. They are detailed in §11.5.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
nlta
  • 1,716
  • 1
  • 7
  • 17
  • wouldn't you want `public virtual void Method1() ` on the base so it's overridable? – jazb Jan 25 '22 at 03:37
  • I'm not interested in a better version of this code. I'm interested in understanding why it behaves as it does. The result doesn't match my expectation (: This is a simplified version of my problem and I cannot change the BaseClass. [Possibly relevant link](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#845-satisfying-constraints) – nlta Jan 25 '22 at 03:39

0 Answers0