-1

I have an IEnumerable<BaseClass> that may contain some objects of type SubClassOfBaseClass. I also have an overloaded method with 2 overloads, each one taking either BaseClass or SubClassOfBaseClass.

When I iterate through the IEnumerable and call the overloaded method for each member, passing it the member as a parameter, it always calls the overload meant for BaseClass, never SubClassOfBaseClass.

Is there an elegant way to get it to call the correct overload - other then manually checking each member of the IEnumerable and cating it to the correct type?

Example code:

public class BaseClass {

}

public class SubClassOfBaseClass : BaseClass {

}

public class Program {
    private static void Method(BaseClass item) {
        Console.WriteLine("base class!");
    }

    private static void Method(SubClassOfBaseClass item) {
        Console.WriteLine("sub class!");
    }

    public static void Main(string[] args) {
        var items = new List<BaseClass>();
        items.Add(new BaseClass());
        items.Add(new SubClassOfBaseClass());

        foreach (var item in items) {
            Method(item);
        }
    }
}

The resulting output would be:

base class!
base class!

...but I need it to be

base class!
sub class!
user884248
  • 2,134
  • 3
  • 32
  • 57
  • [How to call a method overload based on closed generic type?](https://stackoverflow.com/questions/19491928/how-to-call-a-method-overload-based-on-closed-generic-type), [Is it possible to get c# to use method overload of most specific type rather than base type?](https://stackoverflow.com/questions/35770767/is-it-possible-to-get-c-sharp-to-use-method-overload-of-most-specific-type-rathe) – CodeCaster Nov 08 '18 at 09:38
  • 3
    Why don't you define `Method()` as virtual in `BaseClass` and override it? – CodeCaster Nov 08 '18 at 09:38
  • 5
    Since your Collection is of BaseClass Type its Narrow Casting behind the scenes - So Base implementation will be called "Always". – Prateek Shrivastava Nov 08 '18 at 09:38
  • @CodeCaster - thanks for the references. The dynamic keyword seems to be the most appropriate solution to my question. As for defining Method() in BaseClass: That was the first idea I had, but in my specific case (which is different from the basic POC code I wrote above) that might not be the best design. – user884248 Nov 08 '18 at 10:53
  • @PrateekShrivastava - thanks. That is a good explanation of the problem (even though it is not really an answer to my question). – user884248 Nov 08 '18 at 10:54

1 Answers1

1

I tried to post this into the comment section, but I don't have permissions to do that.

However, here is a solution that could work:

According to dynamic - MSDN, try to avoid an iteration with var - use dynamic:

foreach (dynamic item in items) {
        Method(item);
    }

Hope that helps. Good Luck!

movcmpret
  • 179
  • 1
  • 10