It’s Not My Fault — StyleCop and the Default C# Class

12. January 2010 One-Time 0

A while back, I was turned on to StyleCop FxCop’s little brother for ensuring coding styles are maintained. I’ve used it some to clean up my code. Since I’ve been working alone, I haven’t really had any Coding Standards that I live by, other than “Doing what I want.”

The problem is what I wanted when I started one project, is far from ideal. I was naive, foolish, ignorant, you name it. And you can see the evolution of coding practices over the life of the project. So I thought I’d try to make sure I used StyleCop to keep me honest.

One problem has bugged me about it, though. That is, it’s expected layout of a class file. It expects an XML header at the top, followed by namespace declaration, followed by any import/using statements, followed by your class.

Nothing obscene there, I read their rational as to why, and it sounded good to me. I had a few issues, though. My files had headers, but not XML headers. The header comment was followed by the import/using statements, followed by namespace and then class name. It wasn’t really my fault, after all, that’s the layout you get when you do an “Add Class” in Visual Studio.

But that wasn’t good enough, if I wanted a consistent look and feel, I needed to do something better. I started by writing a couple macros to add the correct header at the top of a file. And that works, but it wasn’t enough.

I just recently started a new project, which means all new classes, not just modifying existing code files. And the thought of running this macro every time did not appeal to me. So I modified the default class definition in Visual Studio.

To do this, I went to:
C:Program FilesMicrosoft Visual Studio 9.0Common7IDEItemTemplatesCacheCSharpCode1033Class.zip

I opened up the class.cs file in Visual Studio. I then made some changes. Here’s what my class file looks like now:

// --------------------------------
//
// Copyright (c) PaleLocust. All rights reserved.
//
// ---------------------------------

namespace $rootnamespace$
{
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;

public class $safeitemrootname$
{
}
}

This now generates every new class with an XML header that makes StyleCop happy, as well as putting the usings AFTER the namespace.

I saved these changes, created a compressed folder class.zip (making sure to include class.vstemplate.) I then cut-and-pasted that folder into
C:Program FilesMicrosoft Visual Studio 9.0Common7IDEItemTemplatesCSharpCode1033

Now when I do an “Add Class” the starting format is good to go.


Leave a Reply

Your email address will not be published. Required fields are marked *