Do the null-conditional operator and interpolated strings syntax resolve to just syntactic sugar?
The null-conditional operator (?.
), which allows code clean-up through reducing "excessive" null
checking, and interpolated strings (("\{X}, \{Y}")
), which brings the arguments and format into one, are new features in C# 6.
Do these get compiled to their undesirable counterparts (i.e. the ugly code we sought to avoid)?
I apologize for the naïve question, I don't have the best understanding of languages in general, but I'm curious if it would be possible to run these features on, say, C# 5.
I know this is the case with Java in some instances, is it true as well with these examples?
There isn't a general rule, it differs. Some features are simply syntactic sugar, some add capabilities that weren't possible before, and some are a combination of both.
Syntactic Sugar
String interpolation - This:
string result = $"{bar}";
Instead of:
string result = string.Format("{0}", bar);
Null-propagating operator (?.
) - This:
var result = Foo()?.Length
Instead of:
var temp = Foo();
var result = (temp != null) ? temp.Length : null;
New Capabilities
String interpolation - Also adds support for IFormattable
using FormattedString
so this is possible:
IFormattable result = $"{bar}"
Await in catch/finally - It's now possible to use await
in catch
and finally
blocks:
try
{
}
catch
{
await Task.Delay(1000);
}
There are of course more features in both categories, like exception filters and expression-bodied members.
Like most of the new features in C#6.0, the null-conditional operator is just shorthand (syntactic sugar, if you want to call it) for a pattern of getting the value of a member if the instance the variable being used is not null.
Given a s
of type string
, this:
int? l = s?.Length;
is translated into:
int? l = s == null ? null : s.Length;
And it can be combined with the null coalescing operator (??
):
int l = s?.Length ?? 0;
String interpolation also started as shorthand for string.Format
but evolved to a pattern that can either produce a string
or an IFormatble
. Please, refer to the current spec for more information.
And, by the way, roslyn is the code name for the compiler platform, not the languages or their features.
The Elvis operator is very useful when calling the RaisePropertyChanged event.
In the past you would write
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(nameof(X));
}
But there was a potential multi threading issue if PropertyChanged was set to null before it was invoked. Instead you can write:
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(X));
Which completely avoids the multi threading issue - so it's not quite Syntax sugar.