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).
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.
hi, new to the site, thanks.
ReplyDeletehi, new to the site, thanks.
ReplyDelete