Lazy initialized non-nullable auto properties #7145
Replies: 5 comments 45 replies
-
This can actually be covered by post-initialization logic that runs after initializer block. Currently any post-logic can only be achieved with constructor and its parameters. |
Beta Was this translation helpful? Give feedback.
-
With semi-auto properties this could be achievable with this: public List<Category> Categories { set; get => field ??= new() { Category.Default }; }
public List<string> Tags { set; get => field ??= new(); } |
Beta Was this translation helpful? Give feedback.
-
Does this have any advantage over using System.Threading; // for `LazyThreadSafetyMode`
private readonly Lazy<List<Category>> _categories = new(
LazyThreadSafetyMode.None, // change to desired or remove to imply `None`
() => new List<Category>() { Catgeory.Default });
public List<Category> Categories => _categories.Value; |
Beta Was this translation helpful? Give feedback.
-
Note that for collections that have empty default, you could make the property read-only and use collection initialization syntax: public class Product
{
public required string Name { get; set; }
public List<string> Tags { get; } = new();
}
var p = new Product()
{
Name = "Peaches",
Tags = { "Summer", "Sweet", "Fresh" }
}; |
Beta Was this translation helpful? Give feedback.
-
This was previously suggested in #3247 (comment). |
Beta Was this translation helpful? Give feedback.
-
Currently non-nullable auto properties present a eager initialization problem when they are supposed to have default value. This can lead to redundant initialization and unnecessary GC pressure.
For example a mutable class representing a hypothetical product, specifically designed for non-nullable properties:
An a typical initialization:
The default values for the
Categories
and theTags
properties are redundant in this scenario and only create garbage, Two Lists are created and immediately discarded, becoming GC eligible.Currently the way to avoid this redundant initialization is to convert auto properties to full properties and to use lazy initialization:
The proposal is to allow the
??=
null coalescing assignment operator directly on auto properties initializer like this:This will make lazy initialization for non-nullable auto properties quite easy to implement.
Beta Was this translation helpful? Give feedback.
All reactions