Search code examples
c#genericsgeneric-listgeneric-collections

Get reference to a generic object<T>


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();
}

Solution

  • 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();
    }