If i have a class which accepts a generic type derived from IUser, how can i avoid this error message
Cannot implicitly convert type
ElimCMS.Service.Users.someclass<ElimCMS.DataModel.Users.User>toElimCMS.Service.Users.Isomeclass<ElimCMS.DataModel.Users.IUser>. An explicit conversion exists (are you missing a cast?)
Example
public interface Isomeclass<TUser>
where TUser : class, IUser
{
string test(TUser user);
TUser returnUser();
}
public class someclass<TUser> : Isomeclass<TUser>
where TUser : class, IUser, new()
{
public string test(TUser user)
{
string email = user.EMail;
user.EMail = "changed:" + email;
return email;
}
public TUser returnUser()
{
throw new NotImplementedException();
}
}
Isomeclass<ElimCMS.DataModel.Users.IUser> servicetest = new someclass<ElimCMS.DataModel.Users.User>();
This happens because generics which have different types are not compatible with eachother. To get around this, you can declare your generic parameter to
Isomeclassto be covariant usingHowever, this will break the
testmethod since it will no longer be type safe. To get around this you can change the paramterusertype toIUserand it will work as before.This is dependent on the version of C# that you are using. For some older versions generics cannot be declared as covariant, which means you have to change the assignment target to be of the same type as the object you assign to it.