2

Generating Code using C# Source Generators

 1 year ago
source link: https://vainolo.com/2022/04/20/generating-code-using-c-source-generators/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Generating Code using C# Source Generators

Published by vainolo on 2022-04-20

Code generation is one of those things that divides programmers in two – either you love it or hate it. After having worked many years on a project that used code generation very wisely, I learned how much value it has, but also how dangerous it is. So I understand the haters, but I’m on the side that loves code generation :-). So I was really excited with the announcement of C# Source Generators a while ago, and finally had some time to start looking at this.

I’m not going to repeat the official tutorial because it is easy to follow, and it works (which is not the case in many tutorials…).

Anyway, one small thing that I did add is a way to “see” the code that is generated. Why? Mainly because I like to navigate to the code in my editor. The default settings don’t generate a source file, but after some digging I found you can generate the source files by adding the <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> directive in the project, and voila, the code shows up. Hidden deep down in the compiler directories, but it is there:

You can check out the code for the generator and the program that uses the generator here: https://github.com/vainolo/Vainosamples/tree/master/CSharp/Generators/MyFirstGenerator.

Happy coding!

Advertisements
Report this ad

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK