C# - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C# Nullable types

C# Nullable types

shape Description

C# Nullable types can be applied to stand for all the values of an underlying type, including an additional null value. The Nullable types are instances of System.Nullable<T> which is a  struct.  A nullable type can be declared as a System.Nullable<T> variable or T? variable. T is the underlying type of the nullable type. T can be any value type, including struct, but it cannot be a reference type. The main use of nullable types arises when dealing with databases and other data types that control elements with unassigned values. (For illustration, when the values returned from a table is NULL). Any value from -2,147,483,648 to 2,147,483,647 or null can be stashed away in a Nullable<Int32> variable. Likewise, one can assign true, false, or null in a Nullable<bool> variable. More 

shape Syntax

The syntax for declaring a nullable type is as follows: < data_type> ? <variable_name> = null;

shape Example

[csharp] using System; using System.Collections.Generic; using System.IO; using System.Collections; namespace SPLessons { class Program { static void Main(string[] args) { int? value = null; Console.WriteLine(value.HasValue); value = 10; Console.WriteLine(value.HasValue); Console.WriteLine(value.Value); Console.WriteLine(value); if (value == 1) { Console.WriteLine("True"); } } } } [/csharp] Output:

shape Properties

The HasValue property returns a bool that indicates whether the instance has a value. If the type is null, it does not have a value and HasValue property is false. If the type is assigned to an integer, HasValue is true.