Reputation: 55
I have objects defined as follows:
public class ModelList<T> : ModelBase, IModelList<T>, IModelList
where T : IModelListItem, new()
{
public void Method1()
{
// do work here!
}
}
public class Object1 : ModelListItem
{
}
public class Object2 : ModelListItem
{
}
public class Objects1: ModelList<Object1>, IModelList
{
}
public class Objects2: ModelList<Object2>, IModelList
{
}
Somewhere in code far far away I have a method that will receive a collection object of either Objects1 or Objects2. Is there a way to call Method1 from here?
private void DoSomething(object O)
{
// O can be either Objects1 or Objects2
O.Method1();
}
Upvotes: 1
Views: 353
Reputation: 127543
Because the method does not depend on the type at all, you could add Method1()
to IModelList
and pass that in to the function.
public interface IModelList
{
void Method1();
}
used like
private void DoSomething(IModelList o)
{
// o can be either Objects1 or Objects2 or anything else that implments IModelList
o.Method1();
}
Upvotes: 2
Reputation: 20720
Is there a way to call Method1 from here?
There is: Make your far away method generic:
private void DoSomething<T>(ModelList<T> o)
where T : IModelListItem, new()
{
o.Method1();
}
Upvotes: 5