In this post i will explain what’s the differences between Cast() and OfType() methods using LINQ, and i will also explain when we should use each method.

These methods allow us to cast an object type to another, but when you’re using the Cast() method and exist some object that isn’t of the expected class type, it will throw an exception. If you use the OfType() method, the LINQ query will ignore this objects and it doesn’t throw an exception.


For example, i’m assuming the following Class Diagram:

   

 

And we have the following data objects on the Person’s list:

_persons.Add(new Employee { FirstName="John", LastName="Smith", Age=32, EmployeeNumber=213 });
_persons.Add(new Employee { FirstName = "Mike", LastName = "Stuart", Age = 24, EmployeeNumber = 253 });
_persons.Add(new Employee { FirstName = "John", LastName = "Charles", Age = 53, EmployeeNumber = 214 });
_persons.Add(new Employee { FirstName = "Mary", LastName = "Gomez", Age = 37, EmployeeNumber = 234 });
_persons.Add(new Employee { FirstName = "Javier", LastName = "Matias", Age = 33, EmployeeNumber = 453 });
_persons.Add(new Customer { FirstName = "Bill", LastName = "Smith", Age = 32, Type = CustomerType.Financial });
_persons.Add(new Customer { FirstName = "Jefferson", LastName = "Orton", Age = 32, Type = CustomerType.Retail });
_persons.Add(new Customer { FirstName = "Tom", LastName = "Mowbray", Age = 32, Type = CustomerType.Retail });


Using Cast() to Get all employees that are on the Person’s list

  • LINQ Query:
 List<Employee> employees = Persons.Cast<Employee>().ToList();
  • Query Result:

 

Using OfType() to Get all employees that are on the Person’s list
  • LINQ Query:
List<Employee> employees = Persons.OfType<Employee>().ToList();
  • Query Result: 

              

Well, If you need to get an objects with a specified class type from an object’s list and you only want this objects you should use the OfType() method. However, If you want to ensure that all objects inside the list are a specified class type, you should use the Cast() method.

LEAVE A REPLY

Please enter your comment!
Please enter your name here