carlpett
carlpett

Reputation: 12583

Generic inference of type parameter with constraint to other type parameter

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?

Upvotes: 0

Views: 213

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501103

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.

Upvotes: 2

Related Questions