Hacker News new | ask | show | jobs
by bob1029 1253 days ago
The ability to use source generators in .NET did seem like a really powerful capability when it was first announced.

That said, I have failed to find a practical use case for source generators in my day-to-day work. Reflection is very accessible and we have managed to avoid severe penalties of this on most paths so far.

Has anyone found other good use cases for source generators in their projects?

5 comments

Reflection is inherently unsafe. Even something as relatively simple as a JSON de/serializer can blow up in your face.

Source generators are compile-time safe. Well, unless they generate unsafe code, of course, but most of them shouldn't and don't.

They're also safer in a broader sense in that any "implicit" changes will show up in the version control history, if you commit the generated code (which you should!).

> Reflection is very accessible and we have managed to avoid severe penalties of this on most paths so far.

Performance is not the main issue, it's future changes breaking something that can't be checked at compile-time. Source generators can't break in this way.

Not using reflection also allows safer code trimming.
The number one reason is if you want to make your code AOT friendly, followed by not having to write all the boilerplate required by stuff like INotifyPropertyChanged nor depend on MVVM frameworks for that.
Regular Expressions and System.Json support using source generation for performance gains.