Code Analysis Refactorings

By Michael Flanakin @ 3:22 PM :: 148 Views :: 0 Comments :: Visual Studio, (Open), (Unreported) :: Digg it!

Code analysis is a wonderful thing and so is refactoring. With so many code analysis fixes that are simple refactoring techniques, why not create a simplistic way to refactor code for code analysis tweaks!? Honestly, I'm not surprised it's not in the existing release and I do expect that it will be in there in the future, but I haven't heard of anything like that, so we'll see.

One example is the code analysis performance warning regarding unnecessary casting (CA1800). This comes up a lot when you check to see if a generic object is of a more specific type and then cast it after that check. Instead, the practice is to use the as keyword, which will default to null, if the types aren't compatible. Consider this before and after block as what the refactoring could do...

Before

if (someObject is CustomObject)
    ((CustomObject)someObject).DoSomething();

After

CustomObject custom = someObject as CustomObject;
if (custom != null)
    custom.DoSomething();

Not only is the code easier to read, it's better performing. Then again, I'm not arguing for or against the code analysis. I simply want this simple task automated.

Ratings

Comments

Currently, there are no comments. Be the first to post one!
Click here to post a comment



Archives Archives

Categories Categories

Related Links Related Links