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.
- Generates static
Get{PropertyName}
methods for public properties with public getters. - Generates static
With{PropertyName}
methods for public properties with public setters.
Install the NuGet package:
dotnet add package PropertyMethods.SourceGeneration
-
Mark a type with the attribute:
using PropertyMethods; [GeneratePropertyMethods] public partial record Person(string Name, int Age)
-
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 }; }
-
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
- Target type must be
public
,partial
, and non-static
. - Properties must have public getters (for
Get
methods) or setters (forWith
methods). - Compatible with .NET Standard 2.0 and above.
- Create a .NET project (e.g., console, library).
- Install the package:
dotnet add package PropertyMethods.SourceGeneration
- Add the
[GeneratePropertyMethods]
attribute to apublic partial
type. - Build to generate the methods.
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.