Linger Linger - 2 months ago 15
C# Question

Convert from IEnumerable<T> to IEnumerable<U> via implicit conversion

I am trying to add an implicit conversion to my ViewModel class (VMSalesRep):

public static implicit operator IEnumerable<VMSalesRep> (IEnumerable<QuoteSalesRep> vm)
{
IEnumerable<VMSalesRep> result = vm.Select(x => new VMSalesRep()
{
QuoteSalesRepID = x.QuoteSalesRepID,
FirstName = x.FirstName,
LastName = x.LastName,
CommisionPercentage = x.CommisionPercentage
});
return result;
}


I need to convert an
IEnumerable<QuoteSalesRep>
to an
IEnumerable<VMSalesRep>
. However I am getting the error:


User-defined conversion must convert to or from the enclosing type


What am I doing wrong?

Answer

You can only declare implicit conversions from inside the class that you are coming from or going to. Because of that you would need to put the conversion inside the definition of IEnumerable<T> because that is the type of both your source and destination, which can not be done.

You will not be able to do a implicit conversion from one IEnumerable to another.