Search code examples
c#genericstypesinference

C# generic interface type inference question


I'm not sure how to phrase this question concisely without just giving the example so here goes:

public interface IThing<T>
{
    void Do(T obj);
}

public class ThingOne : IThing<int>
{
    public void Do(int obj)
    {
    }
}

public class ThingTwo : IThing<string>
{
    public void Do(string obj)
    {
    }
}

public class ThingFactory
{
    public IThing<T> Create<T>(string param)
    {
        if (param.Equals("one"))
            return (IThing<T>)new ThingOne();

        if (param.Equals("two"))
            return (IThing<T>)new ThingTwo();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var f = new ThingFactory();

        // any way we can get the compiler to infer IThing<int> ?
        var thing = f.Create("one");

    }
}

Solution

  • No, you can't do this because the result of your Create factory method will be evaluated at runtime based on the value of the parameter. Generics are for compile-time safety and in your case you cannot have such safety because the parameter value will be known only at runtime.