C # syntax sugar ($) (?. )(?? )

Source: Internet
Author: User

Interpolated string ($)

is actually a C # 6.0 pair string. Improved format, identifying string literals as interpolated strings ($)
According to Microsoft's example:

1 usingSystem;2 3  Public classExample4 {5     Public Static voidMain ()6    {7       stringName ="John";8       stringGreeting = $"Hello, {name}!";9 Console.WriteLine (greeting);Ten    } One}

Equivalent to the original string. Format must use placeholders, which are extremely error-prone:

1 string " John " ; 2 string string. Fromat ("hello,{0}! ", name);

The use of $ is not prone to errors and can be written like this:

1 string " John " ; 2 string str = $"hello,{name}! ";


Added syntax sugar: (?. )

This is also the syntax of c#6.0, which is called null-conditional Operator (null conditional operator)
We often need to determine whether the object is null (not judging it will report the exception system.nullreferenceexception), we generally like this:

1 list<stringnull; 2 if NULL )3{4     string[] Strarr = list. ToArray (); 5 }

or this:

1 list<stringnull; 2 string NULL null);

This can be done simply by using this null-conditional operator.

1 list<stringnull; 2 string [] Strarr = list?. ToArray ();

Explain that when the list is null, it does not take the following toarray (), returns NULL when the list is not null toarray ();
Notice here that the front Strarr this is a nullable value.

The null merge operator (?? )

?? operator is called a null merge operator. If the left operand of this operator is not NULL, this operator returns the left operand, otherwise the right operand is returned.
Demo:

1 int null; // a nullable int is set in front of it, so it becomes 0 when you want null. 2 int 0;

C # syntax sugar ($) (?. )(?? )

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.