0

In my code I have several enums with attributes used to associate extra values with them (as per https://stackoverflow.com/a/4778347/6326374). As written, accessing the attribute requires reflection.

C#9 introduced Source Generation, one of the use cases for which is replacing some reflection.

How would I use source generation to replace runtime calls to Attribute.GetCustomAttribute?

nalka
  • 1,894
  • 11
  • 26
Malacandrian
  • 223
  • 1
  • 8
  • [From the FAQ](https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/#can-i-modify-rewrite-existing-code-with-a-source-generator): **Can I modify/rewrite existing code with a Source Generator?** -- No. [...] Source Generators do not allow you to rewrite user source code. We do not intend on allowing them to this. They can only augment a compilation by adding C# source files to it. – madreflection Feb 10 '21 at 18:03
  • *"How would I use source generation to replace runtime calls to Attribute.GetCustomAttribute?"* - you can't. – madreflection Feb 10 '21 at 18:03
  • @madreflection I was aware of this, and didn't think this situation would require rewriting user code. For example, take the Enum validation source generator here https://youtu.be/3YwwdoRg2F4?t=838 it analyses information known about the Enum at compile-time (the values) and produces methods based on that. In my case the compile-time information is the values in the Attribute, and I want to generate a method that returns those values. – Malacandrian Feb 10 '21 at 22:42
  • 1
    What have you tried so far? The only difference between this and reflection is that you have to deal with syntax nodes instead of runtime type metadata. Syntax nodes are a bit different from runtime type metadata, but the concept here is the same: look through the metadata for the attribute you expect, extract the value passed in the constructor (instead of getting it from the property), and that's the value to return. Show your attempt. – madreflection Feb 10 '21 at 22:57

0 Answers0