Why is question mark added after the value type in C #?

Source: Internet
Author: User

In C #, a variable of the value type or reference type is declared. Whether or not an initial value is assigned to the variable, the variable has the default value:

For example, declare the reference type variable: string a, which is equivalent to string a = null. The default value of string is null.
For example, if the declared value type variable is int a, it is equivalent to int a = 0, and the default value of int is 0.

 

Why do we need to set the value type to null?

Let's see the scenario where the value type needs to be null:

 

In a database, the value type can be null, for example, int, decimal, or DateTime. If the corresponding value type in C # cannot be null, when saving data to the database, data types may be inconsistent.

 

For example, in a search scenario, the server declares a variable to receive the value of a field from the client. If this variable is not allowed to be null in C, however, the field value sent from the client may be null (no search condition is selected), which also results in inconsistent data types at the front and back ends.

 

To cope with these scenarios, C # provides a syntax that allows null value types.

 

Description of null allowed value type

DateTime? Date = null; equivalent to: Nullable <DateTime> date = null;
Int? A = null; equivalent to: Nullable <int> a = null;

 

How to avoid throwing an exception because the value type is null?

Use the if... else statement

Int result; if (a = null) {result = 0;} else {result = (int) ;}

Passed ??

Int result = ?? 0;

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.