C# – Nullables

C# provides a special data types , the nullable types, to which you can assign normal range of values as well as null values.

For Example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable <Int32> variables. Similarly , you can assign true, false, or null in a Nullable<bool> variable. Syntax for declaring a nullable type is as follows –

< data_type> ? < variable_name>=

The following example demonstrates use of nullable data types –

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? ( );

// displays the values

Console.WriteLine (” Nullable at show : {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 result –

Nullable at show : , 45, , 3.141

A Nullable boolean value:

The Null Coalescing Operator ( ?? )

The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable ( or not) value type operand, where an implicit conversion is possible.

If the value of the operand is null, then the operator returns the value of the second operand , otherwise it returns the value of the first operand. The following example explains 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 result –

value of num3 : 5.34

value of num3 : 3.14157

Leave a Reply

Your email address will not be published. Required fields are marked *