An hour to learn C # 6

Source: Internet
Author: User

One, string interpolation (string interpolation)

C # 6 We need this when we're stitching strings.

var Name = "Jack"; var results = "Hello" + Name;

Or

var Name = "Jack"; var results = string.Format("Hello {0}", Name);

But in c#6 we can use the new string interpolation feature

  var Name = "Jack";  var results = $"Hello {Name}";

The above is just a simple example, think that if there are multiple values to replace, with the new feature of C#6, the code will be greatly reduced, and readability than before greatly enhanced

new Person {FirstName = "Jack", LastName = "Wang", Age = 100}; var results = string.Format("First Name: {0} LastName: {1} Age: { 2} ", p.FirstName, p.LastName, p.Age);

With the string interpolation:

var results = $"First Name: {p.FirstName} LastName: {p.LastName} Age: {p.Age}";

String interpolation is not just a simple string, you can also insert code directly

Console.WriteLine($"Jack is saying { new Tools().SayHello() }"); var info = $"Your discount is {await GetDiscount()}";

So how do you deal with multiple languages?

We can use IFormattable

How does the following code implement multiple languages?

Double remain = 2000.5;  var results= $"your money is {remain:C}"; # 输出 your money is $2,000.50

Using IFormattable Multi-lingual

Classprogram{static void main (string[] args) {Double remain = 2000.5; var results= chinesetext ($ "Your money is {remain:c}"); Console.WriteLine (results); Console.read (); } public static string chinesetext (iformattable formattable) { Span class= "Hljs-keyword" >return formattable. ToString (null, new CultureInfo ( " ZH-CN ")); }}# output your money is¥2,000.50         
Two, the empty operator (?.)

C # 6 adds a?. operator, which returns NULL when an object or attribute is empty, no longer executes the subsequent code, and nullexception is often present in our code, so we need to add a lot of null judgments, such as

if (user != null && user.Project != null && user.Project.Tasks != null && user.Project.Tasks.Count > 0) { Console.WriteLine(user.Project.Tasks.First().Name); }

Now we can do this without writing the IF directly as follows

Console.WriteLine(user?.Project?.Tasks?.First()?.Name);

This one?. Attributes can be used not only for values, but also for method calls, and if the object is empty, no action will be taken, and the following code will not give an error, and there will be no output.

class Program{    static void Main(string[] args) { User user = null; user?.SayHello(); Console.Read(); }}public class User{ public void SayHello() { Console.WriteLine("Ha Ha"); }}

Indexers that can also be used for arrays

 class program{static void Main ( Span class= "Hljs-params" >string[] args) {user[] users = null; list<user> listUsers = null; //Console.WriteLine (Users[1]?. Name); Error //Console.WriteLine (Listusers[1]?. Name); Error Console.WriteLine (users?[ 1]. Name); //normal Console.WriteLine (listusers?[ 1]. Name); //normal Console.ReadLine ();}}          

Note: Although the above code can let us have a lot less code, but also reduce the empty exception, but we need to be careful to use, because sometimes we do need to throw an empty exception, then use this feature instead hides the bug

Third, NameOf

In the past, we had many places where we needed hard strings, which made refactoring difficult, and once the wrong letters were hard to detect, such as

if (role == "admin"){}

WPF also often has this kind of code

public string Name{  get { return name; }  set { name= value; RaisePropertyChanged("Name"); }}

Now with C#6 nameof, we can do this.

 public string Name{get {return name;} set {name= value; raisePropertyChanged (NameOf (Name)); }} static void main (string[] args) {Console.WriteLine (Nameof ( User.Name)); //output:name Console.WriteLine (nameof (System.Linq)); //output:linq Console.WriteLine (nameof (list<user>)); //output:list console.readline ();}         

Note: nameof only returns the member string, and if there is an object or namespace in front of it, Nameof will only return. In the last part of the nameof, there are many things that are not supported, such as methods, keywords, instances of objects, and strings and expressions

Iv. using await in catch and finally

In previous versions, the C # development team thought it was impossible to use await in catch and finally, and now they implemented it in c#6.

      null;        try        {            res = await Resource.OpenAsync(); // You could always do this.          }        catch (ResourceException e) { await Resource.LogAsync(res, e); // Now you can do this …  }  finally { if (res != null) await res.CloseAsync(); // … and this. }
V. Expression method body

The method body of a sentence can be directly written as an arrow function, and no longer need curly braces

 class program {private static string sayhello ( "Hello World"; private static string jacksayhello () = $ "Jack {SayHello ()}"; static void main (string[] args) { Console.WriteLine (SayHello ()); Console.WriteLine (Jacksayhello ()); Console.ReadLine (); }} 
Vi. Automatic attribute initializers

Before we need to assign the initialization value, this is usually required

public class Person{    public int Age { get; set; } public Person() { Age = 100; }}

But in the new features of C # 6, we're assigning this value

public class Person{    public int Age { get; set; } = 100;}
Seven, read-only automatic properties

In C # 1 We can implement read-only properties like this

public class Person{    private int age=100; public int Age { get { return age; } }}

But when we have automatic attributes, we have no way to implement read-only properties because the automatic attributes do not support the ReadOnly keyword, so we can only narrow access

public class Person{    public  int Age { get; private set; } }

But in c#6 we can implement ReadOnly's automatic attributes.

public class Person{    public int Age { get; } = 100;}
Eight, exception filter Exception filter
   StaticvoidMain (String[] (args) {try {throw new ArgumentException ( "Age");} catch (ArgumentException ArgumentException) when ( ArgumentException.Message.Equals ( "Name") {throw new ArgumentException ( "Name Exception");} catch (ArgumentException ArgumentException) when ( ArgumentException.Message.Equals ( "age") {throw new Exception ( "not handle");} catch (Exception e) {throw;}}      

Before, an exception can only be caught once, now have the filter after the same exception is filtered, as to what is the use, that is a matter of opinion, I think the above example, the definition of two specific exceptions nameargumentexception and Ageargumentexception code are easier to read.

Nine, Index initializer

This is mainly used in the dictionary, as to what use, I do not feel a little use at present, who can know very good use of the scene, welcome to add:

var names = new Dictionary<int, string>        {            [1] = "Jack", [2] = "Alex", [3] = "Eric", [4] = "Jo" }; foreach (var item in names) { Console.WriteLine($"{item.Key} = {item.Value}"); }
The methods of using static classes can use the static using

This function, in my opinion, is also very useless function, but also to remove the prefix sometimes we do not know where this is from, and if there is a method with the same name does not know the specific use of which, of course, proved to use the class itself, but it is easy to confuse it?

using System;using static System.Math;namespace CSharp6NewFeatures { class Program { static void Main(string[] args) { Console.WriteLine(Log10(5)+PI); } }}
Summarize

Above one to eight I think are more useful new features, the latter few I think it is not useful, of course, if you find the appropriate use of the scene should be useful, welcome everyone to add.

Finally, I wish you a pleasant programming.

An hour to learn C # 6

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.