C # Nullable type (Nullable)
C # Nullable type (Nullable)
C # provides a special data type, nullable type (nullable type), nullable types can represent values within the normal range of their underlying value types, plus a null value.
For example,nullable< Int32, read as "Nullable Int32", can be assigned to any value between 2,147,483,648 and 2,147,483,647, or it can be assigned a null value. A similar,nullable< bool > variable can be assigned a value of TRUE or false or null.
The ability to assign null to a numeric type or Boolean is particularly useful when working with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store a value of true or false, or the field may not be defined.
The syntax for declaring a nullable type (nullable type) is as follows:
< data_type>? <variable_name> = null;
The following example demonstrates the use of a nullable data type:
using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
static void Main (string [] args)
{
int? num1 = null;
int? num2 = 45;
double? num3 = new double? ();
double? num4 = 3.14157;
bool? boolval = new bool? ();
// Display value
Console.WriteLine ("Show values of nullable type: {0}, {1}, {2}, {3}",
num1, num2, num3, num4);
Console.WriteLine ("A nullable boolean: {0}", boolval);
Console.ReadLine ();
}
}
}
When the above code is compiled and executed, it produces the following results:
Displays the value of a nullable type:, 3.14157, a nullable Boolean value:
The Null merge operator (?? )
The null merge operator is used to define the default values for nullable types and reference types. The null merge operator defines a preset value for a type conversion in case the value of a nullable type is null. The Null-merge operator implicitly converts the operand type to another nullable (or non-nullable) type of operand of the value type.
If the value of the first operand is null, the operator returns the value of the second operand, otherwise the value of the first operand is returned. The following example demonstrates this:
using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
static void Main (string [] args)
{
double? num1 = null;
double? num2 = 3.14157;
double num3;
num3 = num1 ?? 5.34;
Console.WriteLine ("Value of num3: {0}", num3);
num3 = num2 ?? 5.34;
Console.WriteLine ("Value of num3: {0}", num3);
Console.ReadLine ();
}
}
}
When the above code is compiled and executed, it produces the following results:
Value of num3: Value of 5.34num3:3.14157
The above is the "C # Tutorial" C # Nullable type (Nullable) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!