Skip to content

Gendarme.Rules.Performance.PreferLiteralOverInitOnlyFieldsRule(2.10)

Sebastien Pouliot edited this page Jan 22, 2011 · 2 revisions

PreferLiteralOverInitOnlyFieldsRule

Assembly: Gendarme.Rules.Performance
Version: 2.10

Description

This rule looks for InitOnly fields (readonly in C#) that could be turned into Literal (const in C#) because their value is known at compile time. Literal fields don't need to be initialized (i.e. they don't force the compiler to add a static constructor to the type) resulting in less code and the value (not a reference to the field) will be directly used in the IL (which is OK if the field has internal visibility, but is often problematic if the field is visible outside the assembly).

Examples

Bad example:

public class ClassWithReadOnly {
    static readonly int One = 1;
}

Good example:

public class ClassWithConst
{
    const int One = 1;
}

Notes

  • This rule is available since Gendarme 2.2
Clone this wiki locally