Archive for June, 2007

Simple XML-RPC library

Wednesday, June 20th, 2007

I decided to use the XML-RPC standard in a project I’m working on, and meebey suggested that I release it as a separate project.

So here it is: Org.Cdh.Xmlrpc. Just svn co https://layla.chrishowie.com/svn/Xmlrpc. No fancy reflection stuff yet. The library was designed to encapsulate the XML part of the XML-RPC spec without doing much else. (In other words, you need to handle the HTTP connection and map calls yourself.)

Cast abuse

Tuesday, June 12th, 2007

Every so often when reading through some C# code I’ll run across the as keyword. Now this is a very nifty feature of C#. Just like the familiar parenthetical cast, it returns the object cast to the new type if it succeeds. However, if it fails then it simply returns null instead of throwing an exception.

This is cool when you aren’t sure if you can cast an object to the type you need, but don’t want to force the runtime to test if this can be done twice by using is followed by a parenthetical cast.

It’s markedly not cool when you are not testing if the object you got is null. I see a lot of people doing stuff like (o as Widget).DoStuff(). This is the worst thing you could do here. Why? Because if o cannot be cast to Widget then the result will be null, and a NullReferenceException will be thrown. This will misdirect you to start checking why o is null, when in fact it is not. Using the “old-fashioned” parenthetical cast is appropriate here: ((Widget) o).DoStuff(). If the cast fails you will get the expected InvalidCastException and know immediately what the problem is.

Can someone please explain to me why as is so frequently abused like this?