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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.