Search code examples
c#.netlinq

When to use Cast() and OfType() in Linq


I am aware of two methods of casting types to IEnumerable from an Arraylist in Linq and wondering in which cases to use them?

e.g

IEnumerable<string> someCollection = arrayList.OfType<string>()

or

IEnumerable<string> someCollection = arrayList.Cast<string>()

What is the difference between these two methods and where should I apply each case?


Solution

  • OfType - return only the elements that can safely be cast to type x.
    Cast - will try to cast all the elements into type x. if some of them are not from this type you will get InvalidCastException

    EDIT
    for example:

    object[] objs = new object[] { "12345", 12 };
    objs.Cast<string>().ToArray(); //throws InvalidCastException
    objs.OfType<string>().ToArray(); //return { "12345" }