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
An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.
You can implicitly convert from an expression of type dynamic to any other type. What this means is that the compiler allows an implicit conversion (no cast operator) from the dynamic type to any other type and compilation succeeds.
Type Conversion in C++ Implicit Type Conversion Also known as 'automatic type conversion'. Done by the compiler on its own, without any external trigger from the user.
In C#, you can perform the following kinds of conversions: Implicit conversions: No special syntax is required because the conversion always succeeds and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With