Mega Code Archive

 
Categories / C# Book / 04 LINQ
 

0392 Cast

Cast accepts a nongeneric IEnumerable collection and emit a generic IEnumerable<T> sequence that you can subsequently query: using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Program { static void Main() { ArrayList classicList = new ArrayList(); // in System.Collections classicList.AddRange(new int[] { 3, 4, 5 }); IEnumerable<int> sequence1 = classicList.Cast<int>(); foreach (int i in sequence1) { Console.WriteLine(i); } } } The output: 3 4 5 When encountering an incompatible type Cast throws an exception; using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Program { static void Main() { ArrayList classicList = new ArrayList(); // in System.Collections DateTime offender = DateTime.Now; classicList.Add(offender); IEnumerable<int> sequence1 = classicList.Cast<int>(); // Throws exception foreach (int i in sequence1) { Console.WriteLine(i); } } } The output: Unhandled Exception: System.InvalidCastException: Specified cast is not valid. at System.Linq.Enumerable.d__b1`1.MoveNext() at Program.Main() in c:\g\Program.cs:line 15