Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'System.Collections.IList' to 'System.Collections.Generic.List

Tags:

c#

.net

generics

This is the error I encounter

Error 1 Cannot implicitly convert type System.Collections.Generic.IList<Model.DTO.RoleDTO> to System.Collections.Generic.List<Model.DTO.RoleDTO>. An explicit conversion exists (are you missing a cast?)

My code:

IList<RoleDTO> rl = new List<RoleDTO>();

        rl.Add(new RoleDTO{ roleId = new Guid("D3DCBCDA-AD61-4764-B5A1-057D654F1C26"), 
role = "admin" });


UserDTO user = new UserDTO 
             {
                username = "administrator",
                email = "[email protected]",
                role = rl
             };

And the model:

namespace Model.DTO
{
    public class UserDTO
    {
        public string username { get; set; }
        public string email { get; set; }
        public IList<RoleDTO> role { get; set; }
    }

    public class RoleDTO
    {
        public Guid roleId { get; set; }
        public string role { get; set; }
    }
}

How do I do this correctly?

like image 213
Gerald Hughes Avatar asked May 05 '15 11:05

Gerald Hughes


2 Answers

You are declaring rl as IList, not as IList<RoleDTO>

Change this:

IList rl = new IList<RoleDTO>();

for this:

IList<RoleDTO> rl = new List<RoleDTO>
like image 186
Oscar Avatar answered Sep 16 '22 11:09

Oscar


Just change r1 to be IList<RoleDTO>.

IList<RoleDTO> rl = new List<RoleDTO>();

You cannot mix generic and non generic lists because IList<T> does not inherit from IList and List<T> does not inherit from List and does not implement IList.

EDIT

Based on the new error you have it means that somewhere you are trying to convert a IList<RoleDTO> to a List<RoleDTO> which can not be done implicitly because anyone could write a class that implements IList<RoleDTO>. So you either need to do an explicit cast, or change the types to match. The problem is that your current code does not show anywhere that a IList<RoleDTO> is being implicitly converted to a List<RoleDTO>. But here's some guesses on my part. If UserDTO.roles is actually defined as a List<RoleDTO> instead of IList<RoleDTO> then just change r1 to be defined as a List<RoleDTO> or change UserDTO.roles to be a IList<RoleDTO>. The latter would be my preference. If you are assigning UserDTO.roles to a variable of type List<RoleDTO> you should change the type of that variable to IList<RoleDTO> instead.

like image 39
juharr Avatar answered Sep 18 '22 11:09

juharr