dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

Source generator for lazy properties and methods

Open Rekkonnect opened this issue 1 year ago • 0 comments

Overview

Provide a source generator that will make it quicker to define a lazily-instantiable property value. The underlying mechanism may use the provided System.Lazy<T> type. The generator may also support the partial properties feature introduced in C# 13.

This will be an alternative option to Lombok.NET's Lazy generator. The reason being that Lombok forces an irregular structure, instantiating a class instance to hold the value and refer to its instance holding the globally initialized lazy value. It's also less flexible, not conveniently supporting per-instance lazy instances out of the box.

API breakdown

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, Inheritable = false, AllowMultiple = false)]
public class LazyAttribute(string methodName) : Attribute
{
    public string MethodName { get; } = methodName;
}

Usage example

public class C
{
    [Lazy(nameof(CalculateHeavyName))]
    public partial string HeavyName { get; }

    // assume heavy calculation here
    private string CalculateHeavyName() => string.Empty;
}

Breaking change?

No

Alternatives

As listed above, Lombok.NET offers a source generator for generating lazily-calculated instances. To avoid conflicts with Lombok's Lazy, we could provide an alternative name to the attribute.

Additional context

No response

Help us help you

Yes, I'd like to be assigned to work on this item

Rekkonnect avatar Dec 24 '24 21:12 Rekkonnect