PropertyMethods.SourceGeneration

A C# source generator that automatically creates static Get and With methods for public properties in public partial classes, structs, or records marked with [GeneratePropertyMethods]. Simplifies property access and functional-style updates, especially for immutable records.


Keywords
codegen, source-generator
License
Unlicense
Install
Install-Package PropertyMethods.SourceGeneration -Version 1.0.0

Documentation

PropertyMethods

A C# source generator that automatically generates static Get and With methods for public properties in classes, structs, or records marked with the [GeneratePropertyMethods] attribute. This simplifies property access and functional-style updates, especially for immutable records.

Features

  • Generates static Get{PropertyName} methods for public properties with public getters.
  • Generates static With{PropertyName} methods for public properties with public setters.

Installation

Install the NuGet package:

dotnet add package PropertyMethods.SourceGeneration

Usage

  1. Mark a type with the attribute:

    using PropertyMethods;
    
    [GeneratePropertyMethods]
    public partial record Person(string Name, int Age)
  2. Generated code:

    namespace YourNamespace;
    
    public partial record Person
    {
        public static string GetName(Person person) => person.Name;
        public static Person WithName(Person person, string name) => person with { Name = name };
        public static int GetAge(Person person) => person.Age;
        public static Person WithAge(Person person, int age) => person with { Age = age };
    }
  3. Use the methods:

    var person = new Person { Name = "Alice", Age = 30 };
    Console.WriteLine(Person.GetName(person)); // Outputs: Alice
    var updated = Person.WithName(person, "Bob");
    Console.WriteLine(Person.GetName(updated)); // Outputs: Bob

Requirements

  • Target type must be public, partial, and non-static.
  • Properties must have public getters (for Get methods) or setters (for With methods).
  • Compatible with .NET Standard 2.0 and above.

Setup

  1. Create a .NET project (e.g., console, library).
  2. Install the package:
    dotnet add package PropertyMethods.SourceGeneration
  3. Add the [GeneratePropertyMethods] attribute to a public partial type.
  4. Build to generate the methods.

License

This project is released under the Unlicense, dedicating it to the public domain. You can use, modify, or distribute it without restrictions. See the UNLICENSE file for details.