I am creating an explicit conversion operator to convert between a generic list of entity types to a generic list of model types. Does anyone know why I get the following error:
User-defined conversion must convert to or from the enclosing type
I already have an explicit conversion operator between Entity.objA and Model.objA which works fine. The problem arises when trying to convert the generic list. Is this even possible?
Here is my code:
public static explicit operator List<Model.objA>(List<Entity.objA> entities)
{
List<Model.objA> objs= new List<Model.objA>();
foreach (Entity.objA entity in entities)
{
objs.Add((Model.objA)entity);
}
return claims;
}
Thanks for any help.
The error "User-defined conversion must convert to or from the enclosing type" says exactly what it means. If you have a conversion operator
Then
xxxmust beMyClass. This is what is meant by the "conversion must convert to or from the enclosing type." The enclosing type here isMyClass.The relevant section of the ECMA334 C# spec is 17.9.4:
So here’s your code:
The issue is that for this to be defined as a conversion operator it must reside in the
List<Model.objA>orList<Entity.objA>classes but of course you can not do that as you don’t have access to change those types.You could use
Enumerable.Selectto project to the other type, orList<T>.ConvertAll. For example: