Search code examples
c#constantscode-analysisfxcop

Constant field at compiletime


Is there any way to distinguish a non-constant field and a constant field" at compile time in c#?

I am currently developing c# Code Analysis (FxCop) rules to check the developers' code for inconsistency in naming.

What I have been looking for is a way to target only constant fields. But how are they declared when compiled? Is there like a flag (I have been looking into "HasDefault", but this didn't give me much information).

I am using the FxCop-API (FxCopSdk.dll & Microsoft.Cci.dll). No Reflection is used.

Summing up: How can I distinguish a non-constant field from a constant field with Code Analysis(FxCop), and how can I target the constant.


Solution

  • Researchign further into the FxCop SDK you mentioned, i foudn a field, IsLiteral, which basically means a member which value is specified at compile time.

    Would this work for you?

    E.g

        public class ClassFieldNamePrefixes : BaseIntrospectionRule
        {
            public ClassFieldNamePrefixes() :
                base("ClassFieldNamePrefixes", "TutorialRules.TutorialRules",
                    typeof (ClassFieldNamePrefixes).Assembly)
            {
            }
    
            public override ProblemCollection Check(Member member)
            {
                if (!(member.DeclaringType is ClassNode))
                    return this.Problems;
    
                Field fld = member as Field;
                if (fld == null)
                    return this.Problems;
    
                if (fld.IsLiteral && 
                    fld.IsStatic && 
                    field.Flags.HasFlag(FieldFlags.HasDefault))
                {
                ....
                }
    
                return this.Problems;
            }
        }