FxCop :: Do not declare explicit static constructors. Ignoreable?

I have this utility class nested in annother class and FxCop gives me a Critical warning.

DoNotDeclareExplicitStaticConstructors.html

I don't really think I have annother way to do it. Everything, including the ProductFields, is static or constant.

            public class FieldSets 

         {

                  public static readonly string Minimal;

                  static FieldSets()

                  {

                        CatalogSystemBase.FieldSets.Minimal = CreateFieldSet(ProductFields.ProductID,ProductFields.ProductName);

                  }

                  protected static string CreateFieldSet(string fieldSet,string fieldName)

                  {

                        return  CreateFieldSet(new string[]{fieldSet,fieldName});

                  }          

                  protected static string CreateFieldSet(params string[] fieldNames)

                  {

                        return String.Join(",",fieldNames);

                  }

            }

Added links to ctor stuff.

Perf penalty Static Constructor (Brad Abrams)

http://blogs.msdn.com/brada/archive/2004/04/17/115300.aspx


Quiz: Type Constructors (Brad Abrams)
http://blogs.msdn.com/brada/archive/2004/08/15/214948.aspx  

5 Comments

  • Unless the CreateFieldSet method can throw an exception (which you may want to catch and log for instance in the static constructor), you can move the initialization of the Minimal static variable out of the static constructor and remove the static constructor altogether:



    public static readonly string Minimal = CreateFieldSet(ProductFields.ProductID, ProductFields.ProductName);

  • Excellent, thank you.

  • Since the FxCop HTML page does not explain, what is the problem with declaring explicit static constructors?

  • IIRC it was categorized as a performance issue.



    I believe it is because at runtime, it is continually checking to make sure that the static contructor has been called and (less certain) it may even call it more than once.



    It funny how we approach things sometimes:

    I knew I could assign to the readonly field in the static ctor so I changed them from const fields to readonly but I never even tried what Jason suggested, I had automatically used the static ctor.



  • Thanks for the response--that certainly deserves further exploration, particularly if it is possible for a static constructor to be called more than once.



    Just from a style standpoint, I would tend to prefer explicit static constructors because I don't like assigning a value to a field (static or not) when declaring the field.

Comments have been disabled for this content.