VS2015 new features in preview c#6.0 (i)

Source: Internet
Author: User



The preview version of VS2015 was released on November 12, so let's look at what new features are available in C #.



String Add-interpolation
When formatting a string, string. Format is often used, it is really handy, but it is not convenient to use placeholders and then replace them with parameters, and in c#6.0, the introduction of the string interpolation syntax provides another way to format strings. Take a look at the following example:
Suppose we now have a book class like the one shown below, and now we need to format its fields to output a description of the book.


 
 
public class Book
{
      public int Number { get; set; }

      public string Name { get; set; }

      public string Abstract { get; set; }

      public float Price { get; set; }

      public List<Author> Authors { get; set; }
}

Use String. The code for format is as follows:


 
var introUsingStringFormat = string.Format("[{0}]‘ price is {1:F3}, its description is {2}.", book.Name, book.Price, book.Abstract);


The code that uses string interpolation is as follows:


"[\{book. Name}] ' Price is \{book. PRICE:F3}, its description is \{book. Abstract}. ";

The complete program is as follows:


Public void Show()
{
      //interpolate string
      Var book = new Book
      {
          Abstract = "Book about C#6.0",
          Name = "C#6.0 new feature",
          Price = 10.8709f,
      };

      Var introUsingStrInterPolation = "[\{book.Name}] ‘ price is \{book.Price : F3}, its description is \{book.Abstract}.";
      Var introUsingStringFormat = string.Format("[{0}]‘ price is {1:F3}, its description is {2}.", book.Name, book.Price, book.Abstract);
      Console.WriteLine("format string using string interpolation:");
      Console.WriteLine(introUsingStrInterPolation);
      Console.WriteLine("===================================================== ===========================================
      Console.WriteLine("format string using string.Format method:");
      Console.WriteLine(introUsingStringFormat);
      Console.Read();
} 


For example, the output is the same in both ways:






Summarize:



The string interpolation syntax allows you to insert code directly into a string and specify Format specifier and alignment like String.Format, as in the example above \{book. PRICE:F3} Specifies a precision of 3. This syntax will become more concise in later versions and may be in the following format:


var introusingstrinterpolation = $"[{Book]. Name}] ' price was {book. PRICE:F3}, its description are {book. Abstract}. ";


Empty condition operator?



As shown in the following example, continuous detection of whether an object in an expression is empty is often seen in the program.


 
 if (book != null && book.Authors != null)
 { var countOfAuthers = book.Authors.Count;
 }


Empty conditional operator? Makes this kind of detection more convenient, the expression is more concise, its use method is as follows:


var countofauthersusingnullconditional = Book?. Authors?. Count;


Null condition operator? used in the member operator. And before the index, the following actions are performed:
If the preceding object is empty, return null directly, otherwise allow access to the previous object's members or elements to continue the subsequent operation, so the above expression and the following code snippet are equivalent


 
 if (book == null)
 {
      countOfAuthorsUsingNullConditional = null;
 } else if (book.Authors == null)
 {
      countOfAuthorsUsingNullConditional = null;
 } else {
      countOfAuthorsUsingNullConditional = book.Authors.Count;
 }

The code above shows the logical order in which the execution is performed, with the following concise wording for the same result:


 
if(book == null || book.Authors == null)
{
    countOfAuthorsUsingNullConditional = null;
}

It can be seen from the above that it has the following characteristics:


    1. The expression containing the? Returns a reference type
    2. ? with similar logical operators | | and && short-circuit logic
    3. ? You can make up a chain, as shown in the example above, in a continuous use of the same expression?


In addition, the empty condition operator has the following characteristics:


    1. Only one calculation is performed on whether the object before it is empty
    2. Can be associated with the merge operator?? More convenient to use together
    3. You cannot follow a method call that uses () directly, for event or delegate can be used?. Invoke the way to use, because? Only the right part of it is computed once and saved to a temporary variable, so it is thread safe


Let's look at some examples for 2 and 3:


 
 
//using with coalescing operator ??
int numberOfAuthors = book?.Authors?.Count ?? 0;

//using with delegate.
action?.Invoke();

The complete program is as follows:


 
public void Show()
{ //traditional way if (book != null && book.Authors != null)
     { var countOfAuthors = book.Authors.Count;
           Console.WriteLine("===================using tranditional way==============");
           Console.WriteLine(countOfAuthors);
     } //the way of using null-conditional operator. var countOfAuthorsUsingNullConditional = book?.Authors?.Count;
     Console.WriteLine("===================null-conditional operator==============");
     Console.WriteLine(countOfAuthorsUsingNullConditional);
     Console.Read(); //the logic of the expression. if (book == null)
     {
         countOfAuthorsUsingNullConditional = null;
     } else if (book.Authors == null)
     {
         countOfAuthorsUsingNullConditional = null;
     } else {
         countOfAuthorsUsingNullConditional = book.Authors.Count;
     } //the concise edition using tranditional way. if (book == null || book.Authors == null)
     {
         countOfAuthorsUsingNullConditional = null;
     } else {
         countOfAuthorsUsingNullConditional = book.Authors.Count;
     } //using with coalescing operator ?? int numberOfAuthors = book?.Authors?.Count ?? 0; //using with delegate. action?.
}

nameof-expression



Sometimes we need to get the names of some of the symbol in the code, for example, when the throw ArgumentNullException, we need to get the name of the null parameter (string form), when we call propertychanged, we also need to get the name of the property, Using strings directly has the following drawbacks:


    1. Easy spelling Mistakes
    2. Cannot be refactored
    3. No grammar check


Nameof expressions can return the name of a Parameter object or class member as a string, here are some examples


 
 var nameOfClassPropertyObject = nameof(book);
 var nameOfArgument = nameof(author);
 var classMethodMember = nameof(Book.Equals);
 var classPropertyMember = nameof(Book.Number);
 var @class =  

As you can see from the above example, the nameof operator can be used for classes (including attribute classes), members of classes, objects, and it is important to note that it will only output the final element name without its prefix, such as nameof (book.equals) The output is Equals.



VS2015 new features in preview c#6.0 (i)


Related Article

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.