10 C # features that you really should learn and use

Source: Internet
Author: User

1) async/await

Using the async/await mode, you can not block the UI or the current thread while executing a code block operation. Even if the operation is delayed by certain execution actions (such as a Web request), the async/await pattern will continue to execute subsequent code.

For more information on the async/await model, see: https://msdn.microsoft.com/zh-cn/library/hh191443.aspx

2) object/array/collection initializer (initializers)

You can easily create instances of classes, arrays, and collections by using initializers for objects, arrays, and collections:

12345678 // 示例类publicclass Employee {    public string Name {getset;}    public DateTime StartDate {getset;}} // 使用初始值设定项创建员工实例Employee emp = newEmployee {Name="John Smith", StartDate=DateTime.Now()};

The code in the example above can be very helpful in unit testing, but in some cases it should be avoided, such as when the class should be instantiated by a constructor.

For more information on initializers, see: https://msdn.microsoft.com/zh-cn/library/bb384062.aspx

3) LAMBDA expression, predicate delegate (predicates), Delegate (delegates), and closure (closures)

These features are necessary in many cases (such as when using LINQ), so be sure to learn when and how to use them.

For more information on LAMBDA expressions, predicate delegates, delegates, and closures, see: http://www.codeaddiction.net/articles/13/ Lambda-expressions-delegates-predicates-and-closures-in-c

4)?? –null merge operator (null coalescing operator)

When the left-hand side of the expression is not null,?? operator returns the value to the left of it, otherwise the value to the right of it is returned:

123456 // 可能是 nullvar someValue = service.GetValue();var defaultValue = 23// 如果 someValue 是 null 的话,result 为 23var result = someValue ?? defaultValue;

?? An operator can be used for chained operations:

1 stringanybody = parm1 ?? localDefault ?? globalDefault;

It can also convert nullable types to non-nullable types:

1 var totalPurchased = PurchaseQuantities.Sum(kvp => kvp.Value ?? 0);

More about?? For the contents of the operator, see: https://msdn.microsoft.com/zh-cn/library/ms173224.aspx

5) $ "{x}" – Interpolated string (string interpolation)-C # 6

A new feature of C # 6 that allows string concatenation in a more efficient and elegant way:

12345 // 传统方式var someString = String.Format("Some data: {0}, some more data: {1}", someVariable, someOtherVariable);// 新的方式var someString = $"Some data: {someVariable}, some more data: {someOtherVariable}";

You can also write C # expressions in curly braces, which makes it very powerful.

6)?. –null conditional operator (null-conditional operator) –c# 6

The null condition operator is used as follows:

12 // 如果 customer 或 customer.profile 或 customer.profile.age 为 null 的话,结果都是 nullvar currentAge = customer?.profile?.age;

It's not going to happen again, Nullreferenceexceptions!

More about?. For the contents of the operator, see: https://msdn.microsoft.com/zh-cn/library/dn986595.aspx

7) nameof Expression –c# 6

The new nameof expression may seem less important, but it does have its niche. When using an automatic refactoring tool (such as Resharper), you may need to represent it by the name of the parameter:

12345678 publicvoid PrintUserName(User currentUser){    // 在重命名 currentUser 的时候,重构工具可能会遗漏在文本中的这个变量名    if(currentUser == null)        _logger.Error("Argument currentUser is not provided");    //...}

Now you can write it like this:

12345678 publicvoid PrintUserName(User currentUser){    // 重构工具不会漏掉这个    if(currentUser == null)        _logger.Error($"Argument {nameof(currentUser)} is not provided");    //...}

For more information on nameof expressions, see: https://msdn.microsoft.com/zh-cn/library/dn986596.aspx

8) Property initializer –c# 6

You can specify an initial value when declaring a property by using the property initializer:

12345 publicclass User{    publicGuid Id { get; } = Guid.NewGuid();     // ...}

One benefit of using a property initializer is that you do not have to declare a setter method, which makes the property immutable (immutable). Property initializers can be used in conjunction with the main constructor (Primary Constructor) syntax of C # 6. (Translator Note: Primary Constructor syntax allows you to define a class at the same time, immediately after the class name to specify a constructor with parameters)

9) as/is operator

The IS operator is used to determine whether an instance is of a specific type, such as whether you want to see if the type conversion is feasible:

1234 if(Person isAdult){    //do stuff}

The as operator attempts to convert an object to an instance of a particular class. If it cannot be converted, NULL is returned:

12345 SomeType y = x asSomeType;if(y != null){    //do stuff}
) yield keyword

You can return data items for the IEnumerable interface by using the yield keyword. The following example returns 2 of the sub-Parties (for example, until 8 times: 2, 4, 8, 16, 32, 64, 128, 256):

123456789 publicstatic IEnumerable<int> Power(int number, int exponent){    int result = 1;    for (int i = 0; i < exponent; i++)    {      result = result * number;      yield returnresult;    }}

If used properly, yield can become very powerful. It allows you to delay the generation of objects in the sequence, such as when the system does not need to enumerate the entire collection, and can be stopped on demand.

10 C # features that you really should learn and use

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.