LINQ Casting operations C# with Example



LINQ Casting operations C# with Example

Suppose you have types like the following: 
interface IThing { } 
class Thing : IThing { } 
LINQ allows you to create a projection that changes the compile-time generic type of an IEnumerable<> via the 
Enumerable.Cast<>() and Enumerable.OfType<>() extension methods. 
IEnumerable things = new IThing[] {new Thing()}; 
IEnumerable things2 = things.Cast(); 
IEnumerable things3 = things.OfType(); 
When things2 is evaluated, the Cast<>() method will try to cast all of the values in things into Things. If it 
encounters a value that cannot be cast, an InvalidCastException will be thrown. 
When things3 is evaluated, the OfType<>() method will do the same, except that if it encounters a value that 
cannot be cast, it will simply omit that value rather than throw an exception. 
Due to the generic type of these methods, they cannot invoke Conversion Operators or perform numeric 
conversions. 
double[] doubles = new[]{1,2,3}.Cast().ToArray(); // Throws InvalidCastException 
You can simply perform a cast inside a .Select() as a workaround: 
double[] doubles = new[]{1,2,3}.Select(i => (double)i).ToArray(); 

0 Comment's

Comment Form

Submit Comment