Looking for .net Answers? Try Ask4KnowledgeBase
Looking for .net Keywords? Try Ask4Keywords

.NET Framework Cast


Cast is different from the other methods of Enumerable in that it is an extension method for IEnumerable, not for IEnumerable<T>. Thus it can be used to convert instances of the former into instances of the later.

This does not compile since ArrayList does not implement IEnumerable<T>:

var numbers = new ArrayList() {1,2,3,4,5};

This works as expected:

var numbers = new ArrayList() {1,2,3,4,5};
Console.WriteLine(numbers.Cast<int>().First()); //1

Cast does not perform conversion casts. The following compiles but throws InvalidCastException at runtime:

var numbers = new int[] {1,2,3,4,5};
decimal[] numbersAsDecimal = numbers.Cast<decimal>().ToArray();

The proper way to perform a converting cast to a collection is as follows:

var numbers= new int[] {1,2,3,4,5};
decimal[] numbersAsDecimal = numbers.Select(n => (decimal)n).ToArray();