CommunityToolkit / CommunityToolkit/dotnet

Source generator for lazy properties and methods

Open
#1,033 0 comments 0 reactions 0 assignees View on GitHub
feature request :mailbox_with_mail:
Dominant language
C#
Stars
3.8k
Forks
400
PR merge metrics
No merged PRs in 30d

Description

### 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` 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`](https://github.com/CollinAlpert/Lombok.NET?tab=readme-ov-file#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

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

### Usage example

```csharp
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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.