I have an inheritance structure of objects, somewhat like the following:
public class A { }
public class B : A { }
public class C : B { }
Ideally, I would like to be able to pass a List
of A
, B
or C
to a single method like this:
private void Method(List<A> foos) { /* Method Implementation */ }
B toBee = new B();
B notToBee = new B();
List<B> hive = new List<B> { toBee, notToBee };
// Call Method() with a inherited type. This throws a COMPILER ERROR
// because although B is an A, a List<B> is NOT a List<A>.
Method(hive);
I would like to come up with a way to get this same functionality, with as little code duplication as possible.
The best I can come up with is to create wrapper methods which accept lists of the various types and then loop through the passed lists to call the same method; finally using polymorphism to my advantage:
private void Method(List<A> foos) { foreach (var foo in foos) Bar(foo); }
private void Method(List<B> foos) { foreach (var foo in foos) Bar(foo); }
private void Method(List<C> foos) { foreach (var foo in foos) Bar(foo); }
// An A, B or C object can be passed to this method thanks to polymorphism
private void Bar(A ayy) { /* Method Implementation */ }
Bus as you can see, I have literally copy and pasted that method three times, only changing the type contained in the generic of the list. I have come to believe that any time you start copy and pasting code, there is a better way to do it... but I can't seem to come up with one.
How I can accomplish such a feat without the undesirable copy and pasting?