Search code examples
c#.netfxcopfxcop-customrules

Detecting class with SerializationAttribute in a FxCop custom rule


I'm trying to write a FxCop rule that matches classes that are adorned with the Serializable attribute, but it seems like the attribute is being ignored.

Eg. given this sample class

[Serializable]
[Description]
public class ClassWithSerializableMustHaveSerializableBaseClass : BaseClass
{
}

I would have thought this code from my custom rule would match successfully:

    public override ProblemCollection Check(TypeNode type)
    {
        if (type.Attributes.Any(a => a.Type.FullName == typeof(SerializableAttribute).FullName))
        {                
            var problem = new Problem(GetResolution(), type.SourceContext);

            Problems.Add(problem);
        }

        return Problems;
    }

But it isn't. If I change the matching type to the DescriptionAttribute, then it does work. Is there something magical about SerializableAttribute or have I missed something obvious?


Solution

  • Is there something magical about SerializableAttribute

    Yes; there are a number of attributes that aren't actually embedded as attributes (i.e. are not "custom" sections). Some of the reflection APIs can spoof it so that they appear to be there, but not all of them, and not all of the time (it depends on how the assembly is loaded, for example).

    Examples:

    • [Serializable] - becomes an IL flag on the type
    • [AssemblyVersion] - becomes part of the assembly identity
    • [AssemblyFileVersion] - becomes part of the file identity