0

This might be a silly question but I couldn't find a solution for it.

I have this structure (simplified for brevity):

namespace Test
{
    public interface IEntity
    { }

    public class BaseEntity : IEntity 
    { }

    public class OneEntity : BaseEntity
    { }

    public class Configuration<T> where T : IEntity 
    {

    }

    public class Service 
    {
        public Dictionary<string, Configuration<IEntity>> Configurations = new Dictionary<string, Configuration<IEntity>>();

        public void RegisterConfiguration(string name, Configuration<T> configuration) where T : IEntity
        {
            if(Configurations.ContainsKey(name))
                return;

            Configurations.Add(name, configuration); //Error: Unable to convert Configuration<T> to Configuration<IEntity>
        }
    }
}

I guess I cannot convert a generic type to an interface, but how can I achieve this? I could write RegisterConfiguration as:
public void RegisterConfiguration(string name, Configuration<IEntity> configuration), but then it would fail when I call it with one of my entities (even if they all implement IEntity).

There must be something I did not understand properly with generics but I can't figure out what.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Tinathnath
  • 69
  • 10
  • 3
    Just because two types, `T1` and `T2` exhibit a particular inheritance/implementation relationship, that *doesn't* mean that a single generic type parameterized by those two types (`G`, `G`) exhibits the *same* relationship. (With some exceptions for co- and contra- variance) – Damien_The_Unbeliever Oct 11 '19 at 08:04
  • 3
    Possible duplicate of [Cannot convert from generic type to interface](https://stackoverflow.com/questions/10353494/cannot-convert-from-generic-type-to-interface) – GSerg Oct 11 '19 at 08:06

2 Answers2

3

Try like this:

public class Service<T> where T : IEntity
{
  public Dictionary<string, Configuration<T>> Configurations = new Dictionary<string, Configuration<T>>();

  public void RegisterConfiguration(string name, Configuration<T> configuration)
  {
    if (Configurations.ContainsKey(name))
      return;

    Configurations.Add(name, configuration);
  }
}
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
0

This should work : Reason is you can cast from template to a interface but not reverse and also at class level it should know the template definition

public class Service<T>  where T : IEntity
{
    public Dictionary<string, Configuration<T>> Configurations = new Dictionary<string, Configuration<T>>();

    public void RegisterConfiguration(string name, Configuration<T> configuration) 
    {
        if (Configurations.ContainsKey(name))
            return;

        Configurations.Add(name, configuration); //Error: Unable to convert Configuration<T> to Configuration<IEntity>
    }
}
shahaf
  • 4,750
  • 2
  • 29
  • 32
Ashwini MN
  • 11
  • 2