Preface
I have been using C# to develop programs. .NET has more and more functions and has changed a lot. From the initial closure to the current open source, the functions have been increasing and progressing. Let's take a look at the new C# 6.0 syntax.
As we all know, c# 6.0 was introduced in visual studio 2015. Some features were also introduced in several other versions, such as linq in c# 3.0, dynamic type dynamic in c# 4.0, async and await in c# 5.0, etc.
In C# 6.0, more attention was paid to syntax improvements, rather than adding new features. These new syntaxes will help us write code better and more conveniently.
1. Automatic read-only attributes
The previous attribute is as follows. The attribute assignment needs to be initialized in the constructor.
1 public int Id { get; set; } 2 public string Name { get; set; }
After update
public string Name { get; set; } = "summit"; public int Age { get; set; } = 22; public DateTime BirthDay { get; set; } = (-20); public IList<int> AgeList { get; set; } = new List<int> { 10, 20, 30, 40, 50 };
2. Direct reference to static classes
If the method in the static class was called before, write as follows:
(20d);
After update:
using static ; private void Form1_Load(object sender, EventArgs e) { Abs(20d); }
3. Null condition operator
Previously, when using objects, you need to determine whether it is null
if (student!=null) { string fullName = ; } else { //…… }
After update:
string fullName = student?.FullName; //ifstudentIf empty, returnNull,不If empty, return.FullNaem,Notice!The result must be supportednull
4. String interpolation
string str = $"{firstName}and{lastName}"
5. Exception filter
try { } catch(Exception e) when(("Exception filtering, catch exceptions that meet the criteria") { }
6. The nameof expression can generate the names of variables, types or members as string constants.
(nameof()); // output: Generic (nameof(List<int>)); // output: List
7. Use indexer initialization to assign values to the dictionary
Dictionary<int, string> messages = new Dictionary<int, string> { { 404, "Page not Found"}, { 302, "Page moved, but left a forwarding address."}, { 500, "The web server can't come out to play today."} };
At the same time, the assignment can also be done through indexing
Dictionary<int, string> webErrors = new Dictionary<int, string> { [404] = "Page not Found", [302] = "Page moved, but left a forwarding address.", [500] = "The web server can't come out to play today." };
8. Use Lambda expressions in properties/methods
public string NameFormat => ("Name: {0}", "summit"); public void Print() => (Name);
Summarize
This is the end of this article about the new syntax of C#6.0. For more related content on C#6.0, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!