Idea: coalescing for empty strings or white space #7880
Replies: 4 comments 4 replies
-
Beta Was this translation helpful? Give feedback.
-
public static T? NullIf<T>(this T This, T value)
where T : class
=> object.Equals(This, value) ? null : This; |
Beta Was this translation helpful? Give feedback.
-
If such an operator were to be created, what definition of whitespace should it use? Is The decision about what whitespace means isn't a constant - it varies from project to project, according to the needs of that project. In other words, it's a matter of policy. Any definition of whitespace that got baked into the language would necessarily fit some uses, and not others by definition. A helper method, as suggested by @TahirAhmadov, gives you the policy you need for your project without imposing anything on others. |
Beta Was this translation helpful? Give feedback.
-
This sounds like an XY problem. Why is |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, I have the following idea to make it easier to work with empty strings or white space.
Pretext
Today, we can write null-coalescing code like this:
Output
Problem
The code above would print the empty strings or white space, but I would like them to be coalesced the same as
null
. So, I have to use a ternary operation:Output
Idea
Would it be possible to enhance the null-coalescing operator to handle such strings?
For example,
??-
for empty strings and??~
for white space.This would also work for assignments:
Considerations
In my example, the ternary operation was a simple one-liner, but it can become necessary to introduce a local variable when dealing with calculated strings. Here, a local variable is used to avoid hitting the expensive operation twice:
This could be simplified with the operator, to eliminate the local variable:
The
??-=
or??~=
might be visually confusing so maybe different characters should be used, or maybe such assignments should not be part of the language.Finally, it might be undesirable to add an operator that only works for the
System.String
type, but I'll leave it up to you whether you would open it up for other reference types, or just accept it as an anomaly.Thanks for your time and consideration.
Beta Was this translation helpful? Give feedback.
All reactions