Can one reduce the number of type parameters?

I find it annoying that one has to specify the types of both Foo and FooFactory in the call to RunTest below. After all, if the test knows the type of the Factory, the type the Factory is creating is implied. Assuming I want to run a lot of different factory tests for factories of different classes, that's a lot of angle brackets, and it gets worse with richer type hierarchies. I'm wondering if it is possible to restructure this so that the test is more concise.

public class Foo
{
}

public interface IFactory<T>
{
    T Create();
}

public class FooFactory : IFactory<Foo>
{
    public Foo Create()
      => new Foo();
}

public class FactoryTest
{
    internal void RunTest<TFactory, T>(TFactory factory)
        where TFactory : IFactory<T>
    {
        T t = factory.Create();
        Assert.NotEqual(default(T), t);
    }

    [Fact]
    public void FooFactoryWorks()
    {
        RunTest<FooFactory, Foo>(new FooFactory());
    }
}
Jon Skeet
people
quotationmark

It's not clear that TFactory has to be a type parameter at all. I'd write this:

internal void RunTest<T>(IFactory<T> factory)
{
    T t = factory.Create();
    Assert.NotEqual(default(T), t);
}

Then you can just use:

RunTest(new FooFactory());

as Foo can be inferred by the compiler.

people

See more on this question at Stackoverflow