Detecting class with SerializationAttribute in a FxCop custom rule

138 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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
0
On

It turns out SerializableAttribute is special, and instead you need to check the Flags property:

        if ((type.Flags & TypeFlags.Serializable) == TypeFlags.Serializable)
        {
            var problem = new Problem(GetResolution(type.BaseType.FullName, type.FullName), type.SourceContext);

            Problems.Add(problem);
        }