AmirhosseinYari AmirhosseinYari - 10 months ago 51
C# Question

How can convert a List to another List with explicit operator with out using extention method

I add this operator to my class and works well when I pass a class of "A" it convert to class "B".

public static explicit operator B (A a)
//Convert A to B

but when I want to convert a list of "A" to a List of "B" it doesn't work.
and I try below code but it doesn't work too.

public static explicit operator List<B>(List<A> a)
//Convert List<A> to List<B>

It throw compiler error "User-defined conversion must convert to or from the enclosing type"
I don't want to use extention method to cast it

Answer Source

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();