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;