19

I ran into a problem this week regarding implicit conversions in C# on collections. While this (using implicit) may not be our final approach, I wanted to at least finish out the code to offer the team as an option. I boiled down the problem to the following sample case:

I have two classes in my example: one that represents a business object (Foo) and one that represents the client version (View Object) of this business item (FooVO), as defined below...

public class Foo
{
    public string Id {get; set;}

    public string BusinessInfo {get; set;}
}

public class FooVO
{
    public string Id {get; set;}

    public static implicit operator FooVO( Foo foo )
    {
        return new FooVO { Id = foo.Id };
    }
}

My problem is when I have a a List of Foo objects and want to convert them to a list of FooVO objects using my implicit operator.

List<Foo> foos = GetListOfBusinessFoos(); // Get business objects to convert

I tried

List<FooVO> fooVOs = foos; // ERROR

and

List<FooVO> fooVOs = (List<FooVO>) foos; // ERROR

and even

List<FooVO> fooVOs = foos.Select( x => x ); // ERROR

I know I can do this in a loop, but I was hoping for straightforward (LINQ?) way to convert the objects in one shot. Any ideas?

Thank you in advance.

Edit Fixed typo in example

2
  • 1
    Your implicit conversion to FooVO in that sample is actually returning a Foo, is that intentional? Jun 8, 2011 at 22:17
  • @Chris Walsh - No, that was a typo. I will correct it. Thank you for catching it.
    – SethO
    Jun 8, 2011 at 23:39

4 Answers 4

26

A question much like this gets asked almost every day on SO. You can't do this because doing so violates type safety:

List<Giraffe> g = new List<Giraffe>();
List<Animal> a = g; // Should this be legal?
a.Add(new Tiger()); // Nope; we just added a tiger to a list of giraffes.

In C# 4.0 you can implicitly convert from IEnumerable<Giraffe> to IEnumerable<Animal> because there is no "Add" method to screw things up. But you can never do a "covariant" conversion like that if the conversion of the element types is user-defined. It has to be a reference or identity conversion.

You'll need to create a second list and copy them over one at a time. Or use the LINQ helper methods like Select and ToList to do that work for you.

The name of the type system concept you want is "covariance"; a covariant relationship is one where you reason "Giraffes are animals therefore sequences of giraffes are sequences of animals". If this subject interests you then you can read about how we added covariance (and contravariance) to C# 4.0 here:

http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/default.aspx

Start from the bottom.

6
  • Great example, Eric. Thank you.
    – SethO
    Jun 9, 2011 at 20:09
  • 2
    OP never said FooVO was a subclass of Foo, so a.Add(new Tiger()) wouldn't compile. OP asked about 2 separate classes that need converted to each other. This situation comes up often in MVVM programming. I fetch a List<Customer> from my database and need to convert to a List<CustomerViewModel> for databinding to the view.
    – iupchris10
    Jan 18, 2017 at 15:40
  • 2
    // Nope; we just added a tiger to a list of giraffes. No you added a tiger to a list of animals, which is fine. I fail to see why this would break type safety.
    – LHolleman
    May 3, 2017 at 11:37
  • 2
    @LHolleman: Values of reference types are references. Now is it clear? May 3, 2017 at 13:41
  • It doesn't work when returning a List<Giraffe> from a function that has a return type of List<Animal>
    – DFTR
    Feb 16, 2020 at 20:55
26

The reason your examples don't work is because you are trying to assign an IEnumerable<FooVO> to a List<FooVO>. The following should work.

 List<FooVO> fooVos = foos.Select<Foo,FooVO>(x => x).ToList();
0
12
List<FooVO> d = new List<FooVO>(foos.Select(x => (FooVO)x)); 

Works for me.

2
  • 1
    Aha - casting inside the Select lambda. That works for me as well. Thank you.
    – SethO
    Jun 9, 2011 at 20:22
  • That was the only way to get a cast to work from a .ToListAsync(). Thanks man! Nov 14, 2017 at 19:15
10

Use ConvertAll Method passing in the static implicit operator FooVO( Foo foo ) as the argument

List<FooVO> fooVOs = foos.ConvertAll<FooVO>(FooVO.FooVO);
1
  • 6
    I get a compiler error with my above sample code and your suggestion. However, if I replace (FooVO.FooVO) with (x => x) it will work. I have not used ConvertAll<T>() before - thank you for the suggestion.
    – SethO
    Jun 9, 2011 at 20:21

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.