C#A language that keeps pace with the times

C#A language that keeps pace with the times

Type System

  • Type system: C# is a static type language; variables, parameters, return types, etc. need to be explicitly specified in the code
  • C# 2 introduces a nullable value type, which can be used to effectively represent indeterminate variable values without the use of magic numbers (using -1 as an index of a set, or DateTime.MinValue as a date, and so on).
  • C# 7 also allows users to declare custom structures as immutable types using declarations such as readonly struct. This feature was originally intended to improve the efficiency of code generation by the compiler, but it also helps developers express their code intentions more accurately.
  • C# 8 also plans to add nullable refe
    Rence type. C# 8 assumes that any value declared nullable without display is a non-nullable value, such as the method declaration below
    string Method(string x,string ? y)
    The parameters and types of the method are clear: x is a non-nullable value, y is a nullable value. The return value of the method (without? Symbols) means that the return value of the function is also non-nullable.
  • C# 3 introduces anonymous types and implicit local variables (var) Both are designed to address the drawback of some static type languages: code redundancy. For a data form that is used only in a single method, it is not good to kill chickens with a bull knife if you want to create additional data types specifically for it. The advantage of using anonymous types is that while maintaining the advantage of static type languages, you can clearly and concisely describe the data form.
 var book = new {Title=""Lost in the snow,Author = "Holly Webb"};
 string title = book.Title;
 string author = book.Author;

Anonymous types are mainly used in LINQ query statements, but even without LINQ, it is not advisable to create a data type specifically for a single method. Similarly, if you invoke a construction method of a type, it is not necessary to display the type of the variable declared in the same statement. Which of the following two declarations is simpler and clearer:

Dictionary<string,string> map1 = new Dictionary<string,string>();//Display type
var map2 = new Dictionary<string,string>();//Implicit Type

Implicit types are indispensable when dealing with anonymous types and are increasingly important when dealing with generic types. It is important to focus on distinguishing between the concepts of implicit and dynamic types. Note that the variable map2 in the code above is a static type but does not show its type as written.

  • However, the scope of anonymous types is limited to a single block of code and cannot act on method parameters or return values. C#7Introduces the concept of tuples. A tuple is a value type variable that effectively organizes variables. The framework support for tuples is relatively simple and requires only additional language support to name elements. You can use tuples instead of anonymous types in the previous article:
	var book = { title = "Lost in the Snow",author = "Holly webb"};
The use of tuples instead of anonymous types only applies in some cases. One of the benefits is that tuples can be used as parameters and return values for methods.

More concise code

1. Construction and initialization

First consider how objects are constructed and initialized. **Delegate** should be one of the most evolved and fastest-evolving features. In C# 1, you need to write a method that the delegate can point to, and then a large block of code to create the delegate. For example, subscribe to a new event handling method for a button's C lick event, as shown in the C# 1 code below:

button.Click += new EventHandler(HandleButtonClick);

After C# 2 introduces method group transformations and anonymous methods, you can save the HandleButtonClick method in the following ways:

button.Click += HandleButtonClick;//C#2

If the Click process is simple, you can also write an anonymous method without having to create a separate method:

button.Click += delegate{ MessageBox.Show("Clicked!"); };//C#3

In addition, the closure feature of anonymous functions provides additional benefits: access to local variables in the context of anonymous functions. However, since C# 3 exited lambda expressions, anonymous functions have become increasingly deprecated because lambda expressions have almost all the expertise of anonymous functions, and their syntax is simpler.

button.Click += (sender,args) => MessageBox.Show("Clicked"); //C#3

2. Methods and attribute declarations

  • Auto-implemented properties are one of the most significant features of C#code simplicity. For example, the following code implemented by C#1:
private string name;
public string Name{
	get { return name ;}
	set { name = value; }

If you use an automatically implemented property, you only need one line of code:

public string Name { get; set; }

In addition, the expression subject members introduced by C# 6 further reduce the complexity of the C# language. Suppose there is a class encapsulating the string collection whose C ount and GetEnumerator() members need to be written as follows before C# 6:

public int Count { get { retrn list.Count;} }
public IEnumerator<string> GetEnumerator(){
	return list.GetEnumerator();

With C# 6, you can greatly simplify your code by using the => tag as the body member of the expression:

public int Count => list.Count;
public IEnumerator<string> GetEnumertor()=>list.GetEnumerator();
  • C# 6 introduces an interpolation string literal amount as follows:
throw new KeyNotFoundException($"No calendar system for ID {id} exists")

3. Asynchronous

C#5 uses the async/await mechanism to further simplify the asynchronous programming mode in the mainstream languages. This feature contains two supplements to the async method.

  • The async method generates a return value that represents an asynchronous operation. This part does not require developer intervention at all. The return value is typically Task or Task<T>.
  • The async method consumes asynchronous operations using the await expression. If the async method apostle waits for an incomplete operation, the method pauses asynchronously until the operation is complete.
    With these features, we can write asynchronous code the way we write synchronous code, while bringing concurrent operations closer to a natural way of thinking. With the following sample code, suppose there is an asynchronous method triggered by a WindowsForms event:
private async Task UpdateStatus(){
	Task<Weather> weatherTask = GetWeatherAsync();  	//Start at the same time
	Task<EmailStatus> emailTask = GetEmailStatusAsync();//Two operations
	Weather weather = await weatherTask;		//Wait Asynchronously
	EmailStatus email = await emailTask;		//Complete both
	weatherLabel.Text = weather.Desc;			//Update user interface
	inboxLabel.Text = email.InboxCount.ToString();

Not finished yet...

Tags: C#

Posted on Sun, 10 Oct 2021 13:05:48 -0400 by paha77