Thursday, January 9, 2014

Power of OfType and Cast in Linq

Let’s understand the OfType and Cast with the help of example.

ArrayList states = new ArrayList(4);
states.Add("Karnataka");
states.Add("AP");
states.Add("MP");
states.Add(4);

// Apply OfType() to the ArrayList.
IEnumerable<string> query1 = states.OfType<string>();

foreach (string state in query1)
{
        Console.WriteLine(state);
}
 ---------------------------------------------------------------------
// Apply Cast() to the ArrayList.
IEnumerable<string> query1 = states.Cast<string>();

foreach (string state in query1)
{
        Console.WriteLine(state);
}

OfType

When Converting ArrayList to IEnumerialble using OfType(), it will convert all the elements of type string and ignore the other type. The output of above OfType conversion will be as follows:
Karnataka
AP
MP
Oftype will skip the value 4 as it is not string type and we wanted to convert the ArrayList to IEnumeruable of string type.  If we tried to convert the ArrayList to IEnumeriable, then the output would be:
4

Cast

Will try to cast all the elements of type x(string in above example), if some elements are not of type x then it will throw InvalidCastException. Second for loop stated above in the example will not work as when Cast will try to convert element “4” to string it will throw InvalidCastException.

No comments:

Post a Comment