Friday, December 17, 2010

Conversion Operators - Similarity and Difference between Cast and OfType(T)

Shout it kick it on DotNetKicks.com
Conversion operators use full in number of way. But here in this post I am going to talk about two use full functions Cast<T> and OfType(T) of C# that is use full when you are playing with the non generic collection or untyped object collection or untyped Sequence .  

Cast<TResult>   
TResult - type to convert element of source to.  
Example
ArrayList classicList = new ArrayList();
classicList.AddRange ( new int[] { 3, 4, 5 } );
IEnumerable<int>castSequence = classicList.Cast<int>();

OfType(T)
TResult - type to convert element of source to.
Example
ArrayList classicList = new ArrayList();
classicList.AddRange ( new int[] { 3, 4, 5 } );
IEnumerable<int> ofTypeSequence = classicList.OfType<int>();

Similarity between Cast<T> and OfType(T)
  • Implemented by using Deferred execution.
  • Allows to invoke query operator on non generic collection such as ArrayList.
  • Cannot be applied to collections tat are parameterized by IEnumerable<T>.
  • Returns the Elements in source that can be cast to type TResult ( Resulttype).
Difference between Cast<T> and OfType(T)
Cast<T> throws InvalidCastException when not able to cast all source element in Result type. Where as OfType(T) provide set of element from source which can be convertible in Result type without throwing any error or exception.

Consider below example code to understand this very well.
Add DateTime type to ArrayList with integer elements.

ArrayList classicList = new ArrayList();
classicList.AddRange ( new int[] { 3, 4, 5 } );

DateTime offender = DateTime.Now;
classicList.Add (offender);

IEnumerable<int> ofTypeSequence = classicList.OfType<int>();
IEnumerable<int> castSequence = classicList.Cast<int>();

try
{ 
   Console.WriteLine(ofTypeSequence.Count().ToString()); 
   Console.WriteLine(castSequence.Count().ToString());
}
catch (InvalidCastException ex)
{
   Console.WriteLine("Notice what the offending DateTime element does to the Cast sequence");
}

Output

When you run above code you see exception throws by code at run time when try to display count of element converted by Cast<T>. Where as OfType(T) return count 3 so OfType(T) contains {3,4,5} and eliminate DateTime element.

2 comments: