Suggestion for default property assignment #2001
-
I'd like to make a C# language suggestion. I'm really not sure if this is the right forum to voice this, if not pls point me in the right direction. What I'd like to see is an enhancement to the property initialization that allows you to return an instance of the requested type when the underlying value is null.
Note the use of the
The current auto-property functionality uses the assignment as part of the initialization of the class as if you created the assignment inside the constructor of the class. With the improvements to reduce 'null-ref-exceptions', I feel this could be a great addition and reduce some of the repetitive code. Regards, |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments
-
This is indeed the correct place to make c# language requests. |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
With my favorite proposal #140 this could be written that way: public IList<int> Numbers
{
set;
get => field ?? (field = new List<int>());
} |
Beta Was this translation helpful? Give feedback.
-
null-coalescing assignment is a candidate for C# 8.0, so public IList<int> Numbers
{
set; get => field ??= new List<int>();
} and if the property type is the same as the instance |
Beta Was this translation helpful? Give feedback.
-
Target-typed new-expressions will come with C# 8.0, so public List<int> Numbers
{
set; get => field ??= new();
} (I know, it will not work for the exact OP example) |
Beta Was this translation helpful? Give feedback.
-
Thank you all for your feedback. Looking forward to C# 8.0 :) |
Beta Was this translation helpful? Give feedback.
-
Yes, the |
Beta Was this translation helpful? Give feedback.
null-coalescing assignment is a candidate for C# 8.0, so
and if the property type is the same as the instance
get => field ??= new();
should work too.