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

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" }

Leave a Comment