Using <T> on IPagination

673 views Asked by At

I have the following class

  public class NavigationIEntity
    {
        public int CurrentId { get; set; }
        public string View { get; set; }
        public string Controller { get; set; }
        public IPagination<IEntity> Entities  { get; set; } 
    }

I have the following helper to instantiate

public static NavigationIEntity Create<T>(int currentId, string view, string controller, IPagination<T> entities) where T : IEntity
 {
      return new NavigationIEntity { 
      Entities = entities, View = view, Controller = controller, CurrentId = currentId
      };
}

However i get the following error.

enter image description here

EDIT: I've tried the following, "IPagination entities" ie not T

public static NavigationIEntity Create(int currentId, string view, string controller, IPagination<IEntity> entities)
{
                return new NavigationIEntity { Entities = entities, View = view, Controller = controller, CurrentId = currentId };
}

but don't know how best resolve

enter image description here

DistributionUnit implements IEntity

1

There are 1 answers

1
Yochai Timmer On

You're passing a generic type into a non generic "slot". (Entities is explicitly IEntity)

Generics where is a compiler check, just checks that you're using the object right.

It does not guarantee that the object is of that type at run time.

In your case, because it's explicit anyway, you can do:

public static NavigationIEntity Create<T>(int currentId, string view, string controller, IPagination<IEntity> entities)

It will work for anything that inherits from IEntity anyway.

OR, you can do a little cheat, that will keep the signature the same, but will do what you want:

   public static NavigationIEntity Create<T>(int currentId, string view, string controller, IPagination<T> entities) where T : IEntity
    {
        return new NavigationIEntity
        {
            Entities = entities as IPagination<IEntity>,
            View = view,
            Controller = controller,
            CurrentId = currentId
        };
    }