Home > C#, CodeProject > Cast<> to the rescue!

Cast<> to the rescue!

Just learn’t something today that I’d like to share.

Say you’ve got a generic list of

IQueryable<Person> persons;

that you’d like to convert to

IQueryable<IPerson> iPersons;

where Person : IPerson.

How do you do this? Very simple:

IQueryable<IPerson> iPersons = persons.Cast<IPerson>();

Note that:

IQueryable<IPerson> iPersons = (IQueryable<IPerson>)persons;

won’t work.

Kick It on DotNetKicks.com Shout it
  1. JackU
    March 7th, 2009 at 02:06 | #1

    Also you can use Cast implicitly in a query expression using the following syntax:

    var iPersons = from IPerson person in persons select person;

  2. Nizar
    March 7th, 2009 at 19:48 | #2

    Oh cool! I had no idea. Thanks!

  1. March 5th, 2009 at 01:38 | #1