George Mauer
George Mauer

Reputation: 122102

Why can I not find a custom attribute on this MethodInfo

I have a method with the following signature

    [Specification]
    public void slide_serialization() {

From a point in my code I need to move up the stacktrace to find the closest method with the SpecificationAttribute (performance is not an issue here). I find this method but I cannot find any custom attributes on it.

No custom attributes

I don't think I've ever seen this happen. What might be the reason?

This is a unit testing assembly with Optimization disabled in Build.

Upvotes: 5

Views: 991

Answers (1)

Hans Passant
Hans Passant

Reputation: 941545

The code snippet is not much to go by. But the stack trace makes it pretty clear what happened. Note the <>c_DisplayClass5 type name in the trace. This is an auto-generated class, produced by the C# compiler when it rewrites your code to compile a lambda expression with a closure. The subject of this Q+A.

The slide_serialization() method was rewritten as well, now acquiring the unspeakable <slide_serialization>_b40 method name. Use of angle brackets is intentional, it ensures that the members in the auto-generated code can never collide with identifier names in your program.

And you discovered a restriction in the code rewriting logic in the compiler. It does not transfer [attributes] on the original code to the rewritten code. Whether Microsoft did not think it was important enough to invest the effort or they could not do this correctly for every possible code rewriting rule is unclear. I strongly suspect the latter, the limitation is pretty painful. Usually discovered with much chagrin by programmers that need [SuppressMessage] attribute to get through code analysis without warnings.

There is no simple workaround for this, you have to deal with the limitation.

Upvotes: 5

Related Questions