Chris McGrath’s Blog

Just another Developer’s Blog

Archive for May 2009

Casting in LINQ

with one comment

I recently wrote a LINQ query on a List of WeakReferences. The target of the weak references all implemented my interface (let’s call it IMyInterface). I wanted the query to return a list of all alive IMyInterfaces. It’s a very simple query but was wondering what is the best way to cast the target to IMyInterface? The two ways are…

ref.Where(o => o.IsAlive).Select(o => (IMyInterface)o.Target).ToList();


ref.Where(o => o.IsAlive).Select(o => o.Target).Cast<IMyInterface>().ToList();

The traditional o-o developer in me initially to the first. But then when I thought of the second I couldn’t help but like it. It reads so well from left to right. The only ambiguity it has is whether it is casting each element or the list object to IMyInterface. Maybe it should have been called CastAll or CastEach


Written by Chris McGrath

May 11, 2009 at 12:02 pm

Posted in Blog

Tagged with , , ,