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.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Reddit Post to StumbleUpon

  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

Spam Protection by WP-SpamFree Plugin

Bad Behavior has blocked 249 access attempts in the last 7 days.