Latest web development tutorials

C # nullable type

C # nullable type (Nullable)

C # provides a special datatype, nullable type (nullable type), nullable type can represent values within the normal range of their underlying value type, plus a null value.

For example, Nullable <Int32>, pronounced "may be empty Int32", can be assigned to any value between -2,147,483,648 to 2,147,483,647, it may also be assigned a null value. Similar, Nullable <bool> variable can be assigned to true or false or null.

In dealing with databases and other data types can contain unassigned elements, especially useful for numeric types or Boolean functions will null assignment. For example, the database fields can store values ​​Boolean true or false, or that the field may be undefined.

Declaring anullable type (nullable type) the following syntax:

<Data_type> <variable_name> = null?;

The following example demonstrates an empty data type usage:

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 the value Console.WriteLine ( "type of display value empty: {0}, {1}, {2}, {3}" 
                            num1, num2, num3, num4);
         Console.WriteLine ( "a nullable Boolean value: {0}", boolval);
         Console.ReadLine ();

      }
   }
}

When the above code is compiled and executed, it produces the following results:

Display type can be null values: 45,, 3.14157
An empty Boolean value:

Null coalescing operator (??)

Null coalescing operator is used to define the default value null types and reference types. Null coalescing operator to define a type conversion preset value, can prevent the empty type is Null. Null coalescing operator operand type implicitly converted to another type of operand can be empty (or non-null) value types.

If the first operand is null, then the operator returns the value of the second operand, otherwise the value of the first operand returns. The following example illustrates this point:

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 ( "num3 value: {0}", num3);
         num3 = num2 ?? 5.34;
         Console.WriteLine ( "num3 value: {0}", num3);
         Console.ReadLine ();

      }
   }
}

When the above code is compiled and executed, it produces the following results:

Num3 value of: 5.34
The value num3: 3.14157