FxCop and Guidelines
December 27th, 2004

Brad Abram’s Designing Good Libraries post inspired me to find out if some of the trickier rules mentioned are already caught by FxCop. Obviously many of the casing and naming guidelines are covered.

This code:

    private static string[] _privArray = { "a", "b", "c" };

    /// <summary>
    /// We should not return the static array here,
    /// as the elements can be changed by the caller.
    /// </summary>
    public string[] GetStrings()
        return _privArray;


Is not caught, but this code:

    /// <summary>
    /// We should not expose a static array like this,
    /// because the elements can be changed.
    /// </summary>
    public static readonly char[] InvalidPathChars = { '\"', '<', '>' };


Is found with this message:

Either replace TheClassFromHell.InvalidPathChars with a strongly typed collection that cannot be changed, or replace the public field with a method that returns a clone of a private array.

It seems like it would be pretty easy to adapt that rule to cover the getter method example. Perhaps I’ll add that to my Festivus-vacation to-do list.

This code isn’t caught either, but it seems like it would be more difficult to find.

    /// <summary>
    /// The function should return an empty array instead
    /// of a null array.
    /// </summary>
    public string[] GetStringsNull(bool a)
        if (a)
            return new string[] { "a", "b" };
        return null;


Man, I love FxCop. Partially because of moments like this:

Correct the spelling of the unrecognized token 'Sucky' in namespace 'SuckyLibrary'.

But mostly because it is more efficient and less stressful than reiterating standards ad nauseum.

On the same topic, I was wondering about this:

Using Structs

  • What happens?

    MyStruct[] arr = new MyStruct[10];

  • The constructor for MyStruct is not run here

  • Do not provide a default constructor

It seems to me as if it’s not possible to create a default (parameterless) public constructor for a struct — at least not in C# anyway. Maybe this restriction is not part of the CLR, or maybe we’re talking about constructors with parameters?