Gerald Hughes
Gerald Hughes

Reputation: 6159

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

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?

Upvotes: 20

Views: 76391

Answers (3)

Oscar
Oscar

Reputation: 13960

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>

Upvotes: 4

juharr
juharr

Reputation: 32266

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.

Upvotes: 15

Vishwajeet Bose
Vishwajeet Bose

Reputation: 430

You just need to update the

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

with

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

Upvotes: -1

Related Questions