LINQ Casting operations

suggest change

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<IThing> things = new IThing[] {new Thing()};
IEnumerable<Thing> things2 = things.Cast<Thing>();
IEnumerable<Thing> things3 = things.OfType<Thing>();

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<double>().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();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Casting:
* LINQ Casting operations

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script