Nullable Reference Types of C #8,

Source: Internet
Author: User
Tags processing instruction type null

Nullable Reference Types of C #8,

Xin reminder: The C #8 new feature mentioned in this Article has passed the proposal, but it does not mean that C #8 will be released soon. This means that my notebook may be in vain, and you do not have to rush to understand all the features of this new feature, you may just need to take a look at the "summary" below and explain it clearly.

Summary

The Nullable Reference Types of C #8 indicates that all future test Types cannot be null. For Test Types that can be null, the classification method is similar to the real type that can be null. When declaring a statement, you must add "? "Character. See the following example:

1 int? Num = null; // It can be null (actual type) 2 string? UserName = null; // optional values: null (excluding the test Type) 3 string password = null; // warning: cannot be null! 4 Employee? Emp = null; // It can be null (excluding the test Type) 5 User user User = null; // cannot be null!

There are a lot of new features in this forum, and it is not easy to talk about them. Therefore, the next step is to be longer and longer than the last step.

Large internal volume:

  • Basic knowledge
  • What is Nullable Reference Types?
  • Why does Nullable Reference Types be required?
  • It is not allowed that a Null alternative test Type
    -Default Representation
  • Allow the Null benchmark type
    -Zookeeper Analysis
  • Security Tool
    -Sharplab. io
    -Security token filling function: Nullable Reference Types Preview
  • Both targets
    -Warning of the entire logging Handler

 

Basic knowledge

C # developers have been familiar with the meaning of value types and reference types, and the difference between them:

  • When declaring an actual change (such as int I), if no initial value is specified, then the timer will set it to a different parameter value. For example, the optional value of int type is 0.
  • If you want to make the variability of the actual type null, you must use the generic structure System. Nullable <T>, where T must be the actual type. In C #, can I use a more portable T? Int? Equivalent to Nullable <int>, which represents an integer that can be null.
  • When declaring a variant (such as string s), if the initial value is not specified, its initial value is null. That is to say, the score type changes can be null.

 

So, since the trial model can be null, C #8 (Planning) in the new feature, how does one refer to "Nullable Reference Types? What is it?

TIPS: If you want to download the program first, you can jump to the background first, find out the description about the security C #8 Real-time charge function.

 

What is Nullable Reference Types?

Simply put, before C #8, the test type cannot be null, So C #8 is about to change: all test types cannot be null. If you want to change the value of a test type to null, you must explicitly declare it "can be blank 」. See the following example:

String s1 = null; // C # 7.x OK, C #8 has a warning. String? S2 = null; // C # 7.x loss, C #8 O

 

1st the following warning is reported for the itinerary in C #8:

Warning CS8600: Cannot convert null to non-nullable reference.

Because the string type is of the trial type, as mentioned in the previous article, the trial type is different from the C #8 type and has been changed to the trial settings. It cannot be empty, therefore, the risk generator will issue a warning that null cannot be assigned to "cannot be null 」.

On the other hand, there is no problem with the 2nd stroke model in the C #8 sequence. If the C #7.2 or earlier sequence generator is used, the following error occurs:

Error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'nulllable <T>'

This is because string? It is the Nullable Reference Types variable method of c #8, indicating that a null string variable is to be declared. C #7.2 does not have such a method, so it will appear.

As you can see, the evaluation method of "null test type" and "null test type" has already been implemented in C #8: add a question mark ('? ').

Why does Nullable Reference Types be required?

Before C #8, there are two possible changes in the regression model: null or not null. the compiler cannot help here, therefore, when dealing with changes in the trial model, we often add some "anti-risk Masks", that is, checking whether the changes are null first. For example:

1 static int Length(string text)2 {3     return text == null? 0 : text.Length;4 }

In the previous example, when we wrote the Length function, we could not determine whether the input parameter text has any value. If you do not need to check whether the data is null first, then the calling or method is used, when the program is running, as long as the call end calls a null, the NullReferenceException type will be generated. However, when writing a program, you do not need to forget to add null check in some places to prevent anti-DDoS attacks. Can you please use the browser to help you? (C #8 indicates: Very interesting !)

From the above example, we can see that the existing test type does not have enough intent in the partition null table. We need a more accurate representation to indicate the following values:

  • The variant data of a regression model can be null. Therefore, when accessing the object members represented by the variant, you must first check whether the variable is null.
  • The changes of a certain test type must point to an object, but cannot be null.


Before C #8, we had the first place. C #8 adds Nullable Reference Types to meet the requirements of the second round. In addition, it requires developers to explicitly specify the variables of a certain test type during programming. If they do not understand the settings, otherwise, it cannot be null. In this way, the browser can provide assistance in checking for null, this allows us to avoid problems that may occur when programming.

This feature of C #8 is intended to enable NullReferencException to occur when the number of requests is reduced, without a full credit guarantee-there are too many "eyebrows" and vulnerabilities here, and it is not easy to achieve a hundred percent.

 

It is not allowed that a Null alternative test Type

For example, if you want to make the text parameter Number of the Length method not allow a null value, the original program does not need to be modified, but it is still the same as the original code:

1 static int Length(string text)2 {3     return text == null? 0 : text.Length;4 }

The C #8 compiler recognizes that the plain text must have a value. Therefore, when the call terminal crashes into null, for example:

int i = Length(null);

At this time, the caller can check that the call contains the Response Message of NullReferenceException. Therefore, the caller reports a warning message. Please note that it is very important to only warn users, not just launch the development tool) as a result, there were a lot of sudden Sudden growth trends.

Because it is only a warning, it is recommended that you remove it unless otherwise necessary because it has been added with a null audit. As in the following example, there are some questions about self-defeating tactics:

1 static int Length (string text) 2 {3 return text. Length; // you can call this operation to check whether the cursor is null !). 4}

Because, if the developer ignores the C #8 compiler warning: "null is assigned here to a variable that should not be null .」 So when the program is running, the well-known hacker may appear.

 

Default Representation

When you change the test Type value for a non-null parameter to the preset value, the C #8 runner will receive a warning:

String s = default; // assign null to a variable that cannot be null

 

Allow the Null benchmark type

Extend the example above. If you want to accept null for the parameter text, you need to use the new C #8 Statement, that is, when declaring the change, type. As follows:

1 static int Length (string? Text) // text can be merged into null. 2 {3 return text = null? 0: text. Length; 4}

 

The C #8 compiler will compile the above program as follows:

1 public static int Length([Nullable] string s)2 {3     return (s == null) ? 0 : s.Length;4 }

The full name of the [Nullable] feature is System. Runtime. CompilerServices. NullableAttribute.

Zookeeper Analysis

The parser analyzes the program's route entries to capture places where NullReferenceException may occur. See the following example:

1 static int Length (string? S) // The number of bytes. s can be null. 2 {3 if (s = null) // check whether s is null4 return 0 first; // if it is null, 0 is returned. 5 s = null; // s becomes null again! 6 return s. Length; // The Progress generator can still be reached, and warning: It may be null! 7}

 

However, the program does not have a hundred percent of memory analysis. It should be said that the detection method analysis can only identify the data Declaration of the method itself and the program involved in the region change, but cannot penetrate into other methods called in the method. In the example of a hacker:

1 static int Length (string? S) 2 {3 if (String. IsNullOrEmpty (s) // zookeeper warning: CS8604. 4 return 0; 5 return s. Length; // zookeeper warning: CS8602. 6}

In such a safe method, the browser prompts two warnings! The difference is:

  • Warning CS8604: Possible null reference argument for parameter 'value' in 'bool string. IsNullOrEmpty (string value )'.
  • Warning CS8602: Possible dereference of a null reference.


Cause of the CS8604 warning, yes. We converted the null string variable s into a non-null variable (the IsNullOrEmpty input parameter is declared as string s, so it cannot be null ).

The cause of the CS8602 warning is only mentioned by the hacker. The program cannot go deep into the next call method, so the String cannot be known. the result of the response line of IsNullOrEmpty () is "true" or "false. C # proposes a proposal method for this question, developers are given fewer warnings about the number of attacks that are generated because they cannot analyze Program Programs in depth. This method uses zookeeper (!), Like this:

1 static int Length (string? S) 2 {3 if (String. IsNullOrEmpty (s) // zookeeper warning: CS8604. 4 return 0; 5 return s !. Length; // This line does not cause a warning for the operator. 6}

S! It is telling the reporter: "Hey! Here I know better than you, s will certainly not be null, and you should not give me a warning .」

So, how can we solve another warning CS8604? Currently, I only know these two methods:

  • The warning is blocked by using the optimized choice or pre-processing indication # pragma.
  • Use if (s = null) instead ).


The official github file: The C # Nullable Reference Types Preview mentioned The string. IsNullOrEmpty question. The answer above is:

We are investigating allowing annotations on methods that describe simple relationships between parameters and return value with respect to null values. The compiler cocould use those annotations when analyzing the calling code.


It seems that I can only wait and see the future development.

The signature method is written here first. Next, the security and settings of the tool are better than those of others.


Security Tool

I want to add the Nullable Reference Types Limit Method in Objective C #8. Currently, I have used two methods, one is to use Visual Studio 2017 with the real version of Roslyn connector filling function Nullable Reference Types Preview; the other is to use the connector to open the https://sharplab.io, directly upload the new features of zookeeper and zookeeper C #8.

If you don't want to "get started" your current development environment, then sharplab. io will be a choice. Of course, compared with Visual Studio 2017, the response speed is a little slower than the response speed.

The security or setting methods of the two tools are described below.

Sharplab. io

Easy to use, open the https://sharplab.io with the keyboard, the left pane can be written into the program, in the right pane, you can view the program response result or program response after the ungrouping, including C #, VB, IL, and JIT !).

If you want to implement the Nullable Reference Types of Objective C #8, You must select the version of the zookeeper from the drop-down list on the top of the left pane, as shown in the following example:

 

Then, you can check the program's response results, the warning or warning information displayed by the browser, and the program response after grouping..


Security token filling function: Nullable Reference Types Preview

Prerequisites: Your Visual Studio version 2017 must be 15.5.x in order to install this dynamic feature.

Step 3:

The next time Visual Studio 2017 is opened, the C # compiler should recognize the Nullable Reference Types encoding method.

Note!After installing this Roslyn feature, if you want to install other updates of Visual Studio 2017, you must first remove this feature.


It is worth mentioning that if you have modified the C # version in the selected project, you 'd better check it: Open the program's Properties window, then select Build on the Left Navigation Pane, and then find Advanced press configure at the bottom of the Build settings window. Click here and press "begin" to check the Language version, as shown below:

 

 

After installing the above functions, in my environment, the C # statement version selects latest major version (default) or latest minor version (latest) you can use the Nullable Reference Types encoding method.

These two options allow C # To design and control which new features will appear in the development environment of our users. If you want to renew your subscription, you can choose latest minor. If you prefer to renew your subscription, it will be used only after the new features are officially released, you can select latest major (which combines the new category ). If you want to use a newer version to build your project, select another specific C # version, for example, C #5, 6, or 7.2 ).

There are two categories

After installing the tool in the preceding steps, use Visual Studio 2017 to open a C # project that I previously used to write a dot-text notebook, rebuild the entire solution. As a result, the build is successful, but there are 765 warnings, as shown below:

 

These warnings are:

  • Warning CS8600: Cannot convert null to non-nullable reference.
  • Warning CS8601: Possible null reference assignment.
  • Warning CS8602: Possible dereference of a null reference.
  • Warning CS8618: Non-nullable field 'field-name' is uninitialized.


The number of the last CS8618 is the maximum.

From this point, we can also see that the new features released by C #8 do not produce a "invasive" effect on the existing C # program. I mean, it does not force you to modify or re-compile existing programs. However, every time you build a project, there are so many warning statements, which may cause difficulties. For example, some of the warning warnings that we don't care about may be difficult to find because the warning messages are in a large number of warning messages.

Warning of the entire logging Handler

When you use the new development tool to keep your eyes updated, the simplest and quickest way is to set the statement version in the category definition to a version that is more specific than the actual version. For example, C #6, 7.0, 7.2, and so on. Of course, this is just like fully implementing C #8's new features.

If you want to use some new methods of C #8, but you need to disable some eye-catching warnings, you can set Suppress warnings in the C # program's intended attention window, as shown in the following example:

 

Alternatively, you can set some warnings as warning warnings, that is, you can select Treat warning as errors in the upper limit.

In addition, for a small number of cases, we can also add a pre-processing instruction in the Program # pragma to indicate specific warnings for migration and recovery, as shown below:

# Pragma warning disable CS8618 // Non-nullable field is uninitialized. Program Restart # pragma warning restore CS8618

 

Review

  • Before C #8, the test type can be null, So C #8 is about to change: All test types cannot be null.
  • For variable types that can be null, the classification method is similar to the actual type that can be null. You must add "? ", Such as string? Text ;. This is the Nullable Reference Types encryption method added in C #8.
  • Nullable Reference Types is intended to reduce the chance of NullReferenceException occurring during a period of time, rather than completely without warranty.
  • You can only view the data Declaration of the method and the program involved in the region change. However, you cannot find other methods for calling in the method.
  • For the existing C # program, we can use the new version of the program without modifying the program, and avoid generating a bunch of warning messages during the peak period.

 

After reading this article, I feel that C #8 intends to introduce Nullable Reference Types to reduce the problem of NullReferenceException, which also brings some problems.

So, will the Nullable Reference Types feature be included on the day when C #8 is officially released?

 

Additional information
  • The C # Nullable Reference Types Preview
  • Essential. NET-C #8.0 and Nullable Reference Types
  • Introducing Nullable Reference Types in C #

Related Article

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.