5

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.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
George Mauer
  • 117,483
  • 131
  • 382
  • 612
  • On which .Net Framework version is this? – rene Aug 08 '15 at 20:02
  • @rene been a while, but I believe this was on .Net 4.5 – George Mauer Aug 09 '15 at 19:11
  • @HansPassant so first off, are you saying that [this `NonLambdaCallers` implementation](https://github.com/approvals/ApprovalTests.Net/blob/2ea22b074200fa762f277974ae15cf5073fe9fb2/ApprovalUtilities/CallStack/Caller.cs#L74) is wrong? Second, are you saying that slide_serialazation is somehow not in the stacktrace at all at this point? – George Mauer Aug 09 '15 at 19:18

1 Answers1

5

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.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Thanks Hans - Its been a while since I was in that code base but I'm sure I'll run into it again since for some reason I seem to be one of the few people to lean heavily on the amazing ApprovalTests library which uses Stacktrace walking to generate test names. – George Mauer Aug 09 '15 at 20:26