1

Run it here: http://rextester.com/ZMLMB2576

public interface IClass {
    int number {get;}
}

public abstract class BaseClass : IClass {
    public BaseClass(int n){ 
        number = n+100; 
    }
    public int number { get;set;}
}

public class DerivedClass : BaseClass {
    public DerivedClass(int n) : base(n) { 
        number = n; 
    }
    public int number { get;set;}
}


public class Program
{
    public static void Main(string[] args)
    {
        var foobar = new DerivedClass(1);

        Console.WriteLine(GetNumber(foobar)); // 101
    }

    public static int GetNumber(IClass foo){
        return foo.number;
    }
}

Why does the function GetNumber not use the most derived class and instead only treats the passed object as BaseClass ?

If it was treating the passed object (foo) as DerivedClass then I suspect the base constructor to run first and then DerivedClass constructor, overriding 101 with 1

ParoX
  • 5,685
  • 23
  • 81
  • 152

1 Answers1

1

Shadowing (number in derived class hides one from base) and the fact that interface is implemented by base class leads to this behavior. Mapping interface methods defined by base class and IClass.number is mapped to BaseClass.number which is completely different from DerivedClass.number.

Fixes:

  • make property number to be virtual in base class (more standard approach)
  • derive both classes from the interface so interface actually picks up implementation from derived class (will confuse readers and everyone will try to remove interface from derived thus breaking it again)

    class Derived : BaseClass, IClass { ...
    

Notes:

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179