0

Given these classes:

public abstract class HostBase
{}
public abstract class ConfigBase
{}
public abstract class HostBase<TConfig> : HostBase where TConfig : ConfigBase
{
    protected internal TConfig Config { get; set; }
}
public class GenericHost : HostBase<Config>
{}
public class HostFactory
{
    public static THost Create<THost, TConfig>(TConfig config)
        where THost : HostBase<TConfig>, new()
        where TConfig : ConfigBase
    {
        return new THost { Config = config };
    } 
}

Why can't the compiler infer the type of TConfig from HostFactory.Create<GenericHost>(new Config())? It seems to me that there is only one possible type for TConfig?

I don't get an inference error from the compiler, though:

The type 'GenericHost' must be convertible to HostBase<TConfig> in order to use it as parameter 'THost' in the generic method 'THost HostFactory.Create<THost, TConfig>(TConfig)'

This error seems strange, because this does compile: HostBase<Config> h = new GenericHost().

What am I missing?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
carlpett
  • 12,203
  • 5
  • 48
  • 82

1 Answers1

2

You can't infer just some type parameters within a method call. Generic type inference either infers all type parameters, or none. There's no way of inferring THost from the parameters (there could be multiple classes which derive from HostBase<Config>), which means you basically can't use type inference for that method.

Looking at this specific example, I think you're going to find it tricky to use type inference at all, because of the way the relationships work.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Ah, didn't remember that limitation. And yes, I thought about moving the `THost` parameter to the class, but since I need to constrain it on `TConfig` that doesn't work... The reason for this is that there are other implementations of the non-generic `HostBase`, my goal was to have the same syntax for all instantiations regardless of type. But I guess that isn't possible without changing some of the foundations then – carlpett Jul 15 '13 at 07:52
  • @carlpett: A similar question answered(also by Mr. Skeet) in more detail: http://stackoverflow.com/questions/15619038/is-there-a-syntax-does-a-reversed-type-inference – Ken Kin Jul 15 '13 at 08:10