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 le
List<FooVO> d = new List<FooVO>(foos.Select(x => (FooVO)x));
Works for me.
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();
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.
Use ConvertAll Method passing in the static implicit operator FooVO( Foo foo )
as the argument
List<FooVO> fooVOs = foos.ConvertAll<FooVO>(FooVO.FooVO);