It says "Initialize all static fields in Jnj.ThirdDimension.Controls.ControlPainter when those fields are declared and remove the explicit static constructor." but the static constructor contains only logic that can't be moved to initializers:
public static class ControlPainter
{
static ControlPainter()
{
SetPrintType(typeof(TextBox), PrintType.ExternalPaint);
SetPrintType(typeof(NumericUpDown), PrintType.ExternalPaint);
}
static bool useOnPaint = false;
...
}

Initialize reference type static fields inline
RichWood
Andrew,
That's a bad fix in the example you've given. As the MyStaticInitializer method will only get called if you touch the dummy field, it won't get called if an instance of the class is created.
Not every FxCop violation needs to be fixed. If you read the documentation on this rule (http://www.gotdotnet.com/team/fxcop/Docs/Rules/Performance/InitializeReferenceTypeStaticFieldsInline.html) it states under the When to Exclude Messages section: It is safe to exclude a message from this rule if performance is not a concern; or if global state changes due to static initialization are expensive, or must be guaranteed to occur before a static method of the type is called or an instance of the type is created.
You should consult this section for every new rule you come across to check to see if you should exclude the particular violation for your situation.
In saying that though, we are thinking about changing this rule to not fire on static constructors that don't touch static state, that is, those that don't set or initialize a static field.
Regards
David
shecla
Hi Andrew,
can you provide more details on what SetPrintType does
If it puts some data in a static dictionary or something like this, you could modify your code to initialize this field by calling a method.
e.g.
static Dictionary<Type, PrintType> printTypes = PopulatePrintTypes();
Regards,
Jeffrey
Dato0011
public class Class1
{
static Class1()
{
File.Create("c:\\tmp").Close();
}
}
This can of course be fixed by doing the following:
public class Class1
{
static int dummy = MyStaticInitializer();
static int MyStaticInitializer()
{
if (dummy == 0) // to get rid of "unused variable" warning
{
File.Create("c:\\tmp").Close();
}
}
}
but that's simply ridiculous. Does FxCop basically say that static constructors are evil