Monday 28 July 2008

Resharper 4 Bug with 'Use Format String'

I'd like to say first that I really, really like Resharper 4.0 and have made it my mission to persuade my boss to buy it for all of the Dev's where I work. I got my copy free at a NxtGenUG Southampton meeting and it continues to make my life as a developer easier.

But...

I've come across a small bug in Resharper 4.0 today, so I thought that I'd share so that others become aware.

Real code has been changed to protect the innocent (and because it belongs to my employer).

Start off with a StringBuilder.Append statement that uses the '+' operator to concatenate a string with an object. Why an object, well because that's what the code I'm working with has, not ideal, but that's working with legacy code for you sometimes.

Of course, using the Append statement with string concatenation isn't ideal practice either and what I'd like is to change it to an AppendFormat call. Now Resharper makes this very, very (seductively) simple.

Here's my example code before I let Resharper do its' thing:

Here's Resharper offering to do its' thing:


Here's the code that results:

The important line to note is that we now have:

stringBuilder.AppendFormat("{0} likes Resharper.", (object[])canBeCastToString);

Note the unnecessary cast to an object array. Because of this we now get the error:

System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Object[]'.

The solution is just to get rid of the superfluous cast to Object[].

I still really, really like Resharper 4.0.

No comments: