Null Coalescing Properties #1756
Replies: 8 comments
-
Some of us consider #140, which introduces the Lazy: It takes the pain out of 99% of the asks out there. (And there are a lot by now!) |
Beta Was this translation helpful? Give feedback.
-
@jnm2 I do love the idea of the However, { get => field ??= new(); set; } // Lazy
{ get => field ?? new(); set; }` // Default get
{ get; set => field = value ?? ""; }` // Default set Is still substantially longer than: { get ??= new(); set; } // Lazy
{ get ?? new(); set; }` // Default get
{ get; set ?? ""; }` // Default set The most extreme case here being Default Set, which is nearly half of what it used to be, and is pretty common to use, though the new syntax is indeed a huge improvement as is. |
Beta Was this translation helpful? Give feedback.
-
I do like your syntax in that last comment. It only works if the value you want to replace is |
Beta Was this translation helpful? Give feedback.
-
@jnm2 Yes, but |
Beta Was this translation helpful? Give feedback.
-
I'd had a similar idea, which I mis-posted here: dotnet/docs#17922. I'd proposed '??=' rather than '??', which is effectively syntactic sugar over 'field ??= Thing2'. |
Beta Was this translation helpful? Give feedback.
-
The case I'd been trying to address was actually parameters that default to other fields:
becoming
|
Beta Was this translation helpful? Give feedback.
-
@kfsone Your proposed operator is practically guaranteed to not happen because as of C# 8.0, You're gonna be better off waiting for #140 (which has a very real chance of coming out with C# 9.0), at which point you can write your case as public string PreferredName { get => field ?? FirstName; set; } = null; |
Beta Was this translation helpful? Give feedback.
-
@Joe4evr I'm aware of the null-coalescing operator, I was actually intentionally reusing it:
but the field syntax is nice and explicit, so I'm going to wait on that :) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Problem
I saw recently some code that looked something like this:
I thought that that was a fairly common use for properties, but that's an awful load of code for such a simple idea.
Purposed Syntax:
We could even allow for this syntax, where it will automatically call the default constructor if the value is null. If there is no parameterless constructor, a compile error will be thrown.:
This removes a lot of that fluff and better shows what's going on, taking up much less space.
Beta Was this translation helpful? Give feedback.
All reactions