Thursday, June 24, 2010

Cast() VS OfType()

Fundamentally, Cast() is implemented like this:
public IEnumerable Cast(this IEnumerable source)
{
  foreach(object o in source)
    yield return (T) o;
}
Using an explicit cast performs well, but will result in an InvalidCastException if the cast fails.
A less efficient yet useful variation on this idea is OfType():
public IEnumerable OfType(this IEnumerable source)
{
  foreach(object o in source)
    if(o is T)
      yield return (T) o;
}
The returned enumeration will only include elements that can safely be cast to the specified type.

0 comments:

Post a Comment