0

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?

Linger
  • 14,942
  • 23
  • 52
  • 79
  • 1
    Please check this you cant do this http://stackoverflow.com/questions/1971925/explicit-conversion-operator-error-when-converting-generic-lists#1971935 – inan Sep 28 '16 at 17:43
  • Company I work for provides search engine just for such case - you get an error - put it in and get an answer - https://www.bing.com/search?q=User-defined+conversion+must+convert+to+or+from+the+enclosing+type (granted, there are other usages too), you may try other search engines too like https://www.google.com/?gws_rd=ssl#q=User-defined+conversion+must+convert+to+or+from+the+enclosing+type – Alexei Levenkov Sep 28 '16 at 17:46

1 Answers1

4

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.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431