Suggestion: null-conditional default value operator #784
Replies: 6 comments
-
For your certificate, you can use For the others... this only seems to take away control from manually specifying the default case, e.g. I personally don't see the value in this. (I also don't like the use of the underscore here.) |
Beta Was this translation helpful? Give feedback.
-
compare: Didn't know that all nullable type comparisons with null return false. Thanks, that is helpful. I don't particularly care what symbol is used to represent the operator as long as it starts with a question mark. |
Beta Was this translation helpful? Give feedback.
-
_IsEmployee is already a valid name in C#. |
Beta Was this translation helpful? Give feedback.
-
.NET has default values, but the result of a null-condition is always a nullable, not a default value. In most cases it wouldn't make sense for the expression to result in a default value for the case of a value type, and for the cases where it does you already have the option to use the null-coalescing operator ( |
Beta Was this translation helpful? Give feedback.
-
Similar to #328. If what's important is to default to a specific value like |
Beta Was this translation helpful? Give feedback.
-
I think a better solution would be to allow overloading the ?. operator. That way we could specify exactly what we mean by default state, rather than fixing it in the language. IIRC, guys from Unity Engine had this as a major request, they use a "null object" in places, and also override ==, Equals etc. in the base class for all objects. Now since ?. is not overloadable there is an issue with that. I'm pretty sure the C# team knows about this though. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
The
?.
operator is great for working with objects. It's not so great for working with value types.Consider an certificate that may or may not be null. I would like to check if I have a certificate and if the certificate has a length greater than zero. Today, I write
if (cert != null && cert.Length != 0)
.Consider an object person that has a boolean property IsEmployee. I would like to know if person is null (anonymous / no authentication and if the person is an employee). Yesterday, I wrote
if (person != null && person.IsEmployee)
. Today, I writeif (person?.IsEmployee == true)
. This works, but is a bit awkward (particularly fora?.b != true
)Introducing a new operator
?_
.a?_b
means(a == null : default(typeof(b)) : a.b)
.So, in my first case, I would write:
if (cert?_Length > 0)
.In my second case, I would write:
if (person?_IsEmployee)
.Interestingly,
?_
would actually have the same meaning as?.
for reference type properties. That is, ifb
is an object thena?_b
would equala?.b
for all possible values ofa
.Beta Was this translation helpful? Give feedback.
All reactions