Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

roslyn - Null-conditional operator and string interpolation in C# 6

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...