2
votes

I am trying to implement generic class using code below:

interface IBasicInput<T> where T : InputOutputConfig
{
    void Configure<T>(ConfigurationDictionary<T> conf) where T : InputOutputConfig;
}

public class ConfigurationDictionary<T> : Dictionary<string,T> where T : InputOutputConfig
{    
}

public abstract class InputOutputConfig
{   
}

public class SpecificInputConfig : InputOutputConfig
{
}    

public class GenericInput<T> : IBasicInput<T> where T : InputOutputConfig
{
    ConfigurationDictionary<T> configuration;

    public GenericInput()
    {
        configuration = null;
    }

    public void Configure<T>(ConfigurationDictionary<T> _conf) where T : InputOutputConfig
    {
        configuration = new ConfigurationDictionary<T>();
        foreach (KeyValuePair<string,T> kvp in _conf)
        {

        }
    }
}

The isssue is that configuration = new ConfigurationDictionary<T>(); generates error.

Error CS0029 Cannot implicitly convert type 'ConfigurationDictionary [GenericsTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]' to 'ConfigurationDictionary [GenericsTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]'

This message does not make sense to me since it basicly says it cannot convert "typeA" to "typeA". Could someone explain what is wrong with this code?

1
Your issue is because you've got a two generic type parameters called T within the scope of your Configure methodjamespconnor

1 Answers

7
votes

You have shadowed your class' T template parameter with your functions T template parameter. And they might not be the same.

Either give your inner T another name like T2 or maybe drop it alltogether if you meant to use your class' T anyway:

public class GenericInput<T> : IBasicInput<T> where T : InputOutputConfig
{
    ConfigurationDictionary<T> configuration;

    public GenericInput()
    {
        configuration = null;
    }

    public void Configure<T2>(ConfigurationDictionary<T2> _conf) where T2 : InputOutputConfig
    {
        // in this line, you need the class template T, not the inner T2
        configuration = new ConfigurationDictionary<T>();

        foreach (KeyValuePair<string,T2> kvp in _conf)
        {

        }
    }
}