Skip to content

Gendarme.Rules.Performance.PreferLiteralOverInitOnlyFieldsRule(git)

Sebastien Pouliot edited this page Mar 2, 2011 · 1 revision

PreferLiteralOverInitOnlyFieldsRule

Assembly: Gendarme.Rules.Performance
Version: git

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

Source code

You can browse the latest source code of this rule on github.com

Clone this wiki locally