I added this conversion operator to my class and it works well.
When I pass an object of class A
, it converts it to an object of class B
.
public static explicit operator B(A a)
{
//Convert A to B
}
But when I want to convert a List<A>
to a List<B>
, it doesn't work.
I tried the following code, but it doesn't work either.
public static explicit operator List<B>(List<A> a)
{
//Convert List<A> to List<B>
}
Instead, it throws the following compiler error:
User-defined conversion must convert to or from the enclosing type.
I don't want to use an extension method to cast it.
You can't use Conversion Operators for converting list of one type to another.
C# enables programmers to declare conversions on classes or structs so that classes or structs can be converted to and/or from other classes or structs, or basic types.
As you see, the purpose is to convert one type to another, not the list of that types.
You can use Select
method instead of that:
List<B> listB = listA.Select(a => (B)a).ToList();