Tinathnath
Tinathnath

Reputation: 69

C# How to cast a generic type to interface it implements

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.

Upvotes: 0

Views: 104

Answers (2)

Ashwini MN
Ashwini MN

Reputation: 11

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>
    }
}

Upvotes: 0

Michał Turczyn
Michał Turczyn

Reputation: 37367

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);
  }
}

Upvotes: 3

Related Questions