Search This Blog

Monday, January 10, 2011

Difference between Cast and OfType Operators in LINQ?

Cast Operator:
  • It casts each element in a collection into the type we want to.
  • Any Exceptions if found are raised.
ex: 
ArrayList arrayList = new ArrayList();
arrayList.Add("Adams");
arrayList.Add("Arthur");
arrayList.Add("Buchanan");
IEnumerable<string> names = arrayList.Cast<string>().Where(n => n.Length < 7);
foreach(string name in names)
Console.WriteLine(name);



Of Type Operator:
  • It casts only those elements in the collection that can be type casted into the type we want.
  • No Exceptions are raised in this case.
ex:
ArrayList arrayList = new ArrayList();
arrayList.Add("Adams");
arrayList.Add("Arthur");
arrayList.Add("Buchanan");
IEnumerable<string> names = arrayList.OfType<string>().Where(n => n.Length < 7);
foreach(string name in names)
Console.WriteLine(name);

No comments:

Post a Comment