SoFunction
Updated on 2025-03-07

A summary of 10 common features in C#

1) async / await

Using async / await mode, you can not block the UI or the current thread when executing code block operations. Even if the operation is delayed by some execution action (such as a web request), the async/await mode will continue to execute subsequent code.

Microsoft Documentation:/zh-cn/library/

2) Initializers for object/array/set

By using initializers for objects, arrays, and collections, it is easy to create instances of classes, arrays, and collections:

// Sample class
public class Employee {

  public string Name {get; set;}

  public DateTime StartDate {get; set;}

}

// Create an employee instance using initializer
Employee emp = new Employee {Name="John Smith", StartDate=()};

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

Microsoft Documentation:/zh-cn/library/

3) Lambda expressions, predicates, delegates and closures

4) ?? – null coalescing operator

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

// It may be null
var someValue = ();

var defaultValue = 23

// If someValue is null, the result is 23
var result = someValue ?? defaultValue;

?? operators can be used for chain operations:

string anybody = parm1 ?? localDefault ?? globalDefault;

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

var totalPurchased = (kvp =>  ?? 0);

document:/zh-cn/library/

5) $"{x}" – String Interpolation - C# 6

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

// Traditional way
var someString = ("Some data: {0}, some more data: {1}", someVariable, someOtherVariable);

// New way
var someString = $"Some data: {someVariable}, some more data: {someOtherVariable}";

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

6) ?. – null conditional operator – C# 6

The null conditional operator is used as follows:

// If the customer is null, the result is null
var currentAge = customer?.profile?.age;

No more NullReferenceExceptions!

document:/zh-cn/library/

7) nameof expression – C# 6

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

public void PrintUserName(User currentUser)

{

  // When renaming the currentUser, the refactoring tool may miss this variable name in the text
  if(currentUser == null)

    _logger.Error("Argument currentUser is not provided");

  //...

}

Now you can write this:

public void PrintUserName(User currentUser)

{

  // Refactoring tool won't miss this
  if(currentUser == null)

    _logger.Error($"Argument {nameof(currentUser)} is not provided");

  //...

}

document:/zh-cn/library/

8) Attribute Initial Value Settings – C# 6

You can specify an initial value when declaring a property through the attribute initial value setting item:

public class User

{ 

  public Guid Id { get; } = (); 

  // ...

}

Use attributes to start

One advantage of using attribute initializers is that you don't have to declare a setter method, making the attribute immutable. The attribute initializer can be used in conjunction with the primary constructor syntax of C# 6. (Translator's note: The Primary Constructor syntax allows you to specify a constructor with parameters immediately after the class name while defining a class)

9) as / is operator

The is operator is used to determine whether an instance is of a specific type, for example, if type conversion is feasible:

if (Person is Adult)

{

  //do stuff

}

The as operator attempts to convert an object to an instance of a specific class. If the conversion cannot be converted, it will return null:

SomeType y = x as SomeType;

if (y != null)

{

  //do stuff

}

10) yield keywords

You can use the yield keyword to return data items of the IEnumerable interface. The following example returns to the power of 2 (for example until the power of 8: 2, 4, 8, 16, 32, 64, 128, 256):

public static IEnumerable<int> Power(int number, int exponent)

{

  int result = 1;

  for (int i = 0; i < exponent; i++)

  {

   result = result * number;

   yield return result;

  }

}

If used properly, yield becomes very powerful. It causes you to delay generating objects in the sequence, such as when the system does not need to enumerate the entire set, it can stop as needed.

The above is the detailed content of the 10 common features of C#. For more information about common features of C#, please pay attention to my other related articles!