Nullable string concatenation operator #7592
Replies: 3 comments
-
public static TProp? IfNotNull<TValue, TProp>(this TValue? This, Func<TValue, TProp?> getProp)
where TValue : class
where TProp : class
{
if (This == null) return null;
return getProp(This);
}
string? s = ConfigurationManager.AppSettings["MyKey"].IfNotNull(x => x.TrimEnd("/") + "/"); |
Beta Was this translation helpful? Give feedback.
-
My personal preference would be a |
Beta Was this translation helpful? Give feedback.
-
There is a gap in support between nullable number operations and nullable operator overloads. For example: int? a = ...;
int? b = ...;
int? c = a + b; // will be `null` if either `a` or `b` is null
// lowered as:
int? c = a is int aTemp && b is int bTemp
? aTemp + bTemp
: null; Such operations not naturally extending into operator overloads could be an annoying problem. I, personally, could see such "nullable aware" operators making sense if done like the proposal, just more generic (would work on any operator, not just addition). In such a case, the proposal would be lowered as such: string? result = ConfigurationManager.AppSettings["MyKey"]?.TrimEnd("/") is string temp
? string.operator+(temp, "/")
: null; Of course, the XY problem shows up here. As @jnm2 suggested: if your problem is normalizing directory separators, have a function that does that for you. Or better yet, have a type that abstracts that all away. It's a bit unfortunate that many programming languages expect you to treat paths as strings, when that's really just a nice visual representation of the list-like structure they are. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
One of (many) use cases is that I find myself retrieving items from configuration files where I need to make sure that if a string is present it must end with a slash ("/"). To do this, I can do
ConfigurationManager.AppSettings["MyKey"]?.TrimEnd("/") + "/";
, however when MyKey is null you get just the slash back which might not be ideal for many cases.I'm aware we can write a check to see if a key exists and so on.
?+
being an example of such operator we could then do something like this:ConfigurationManager.AppSettings["MyKey"]?.TrimEnd("/") ?+ "/";
Which when left left-hand side returns null/empty string, nothing is appended, and thus we get an empty string or null back, and remove an explicit check for the value coming back from the config before attempting to concatenate.
Beta Was this translation helpful? Give feedback.
All reactions