C# replace/original and Source Generators – part 2

In this post I want to look a little bit closer on the proposed syntax (original/replace) and proposed use cases (Code Generator Catalog). This should help those still unconvinced that it’s the feature. The feature which could make C# developers bend the reality of boilerplate code to their will; but why stop on boilerplate…?

-> Previous post (part 1)

Use cases


I think the most iconic INotifyPropertyChanged-implementing generator is also a good demo of syntax, so let’s start with it:

// PersonViewModel.cs
partial class PersonViewModel
    public string FirstName { get; set; }

Generated file:

// GeneratedSource/INPCGenerator/PersonViewModel.cs
using System.ComponentModel;

partial class PersonViewModel : INotifyPropertyChanged
    public replace string FirstName
        get => original;
            if (original == value) return;
            original = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FirstName));

All of this code, generated. It could cache EventArgs. It could invoke PropertyChanging. Whatever you want – written once in generator it becomes a reality for dozens or hundreds of your files, each with a dozen properties. So much saved time, so much code that won’t become corrupted by a simple mistake. But this is just a tip of an iceberg.


This is not a game changer, as we already have a fair amount of quite convenient libraries for just that purpose. However they all have to use reflection at some point and cache the results. With SourceGenerators that would be simply added at compile time. You could have extensible generator libraries that would allow complete customization of the process and yet write it just once and have that custom behavior in any class you want.

Aspect-Oriented Programming

AOP is probably the most interesting part in terms of actual code improvement. The ability to wrap or replace functions based on realistically any requirement possible to check syntactically or semantically is beyond anything you can do today — that is, assuming that debugging experience would actually use the generated code files and provide friendly experience with the replace/ original feature.

Cold reality

As awesome as I hope this feature seems to you, dear reader, after lecture of my posts – I have to splash your head with cold water. This is a huge feature. It may, or may not come at all. If it will, it surely won’t be this year (duh!), but also not the next, and the one after — or at least it shouldn’t be expected to. You can follow the discussion on GitHub and take a look at a catalogue of ideas for generators.

Written with StackEdit.

Leave a Reply

Your email address will not be published. Required fields are marked *