Chris McGrath’s Blog

Just another Developer’s Blog

Posts Tagged ‘Code

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 , , ,

dotNet Tip: Path.Combine

leave a comment »

A long time ago when I was new to the dotNet framework I was doing a fair bit of File IO. The thing that annoyed me most was checking if a path ended with a slash before appending something to the end. I then found out about

System.IO.Path.Combine(path1, path2);

I’m just doing a bit of IO at the moment and I’m so glad I remembered this. It turns

string path = WindowsDir;
if (!path.EndsWith(‘\\’)) path += “\\”;
path += “Help”;

To simply

string path = Path.Combine(WindowsDir, “Help”);

Written by Chris McGrath

April 20, 2009 at 6:20 pm

Posted in Blog

Tagged with ,

Extended DataGridView for WinForms

leave a comment »

I while back I made a extension to the DataGridView and an article about it. For those who still have to use WinForms I would highly recommend it.

It’s avaliable on CodeProject at Extending the DataGridView.

Written by Chris McGrath

April 6, 2009 at 6:47 am

Posted in Blog

Tagged with , ,