C# Nullable Int

Int keyword

A nullable int can store null. Nullable types are constructed by specifying the question mark after a value type in a declarator statement. The nullable int can be specified with the syntax "int?".

Int

Example

Note

First, this example program demonstrates a use of the nullable integer type. This type is specified with the "int?" syntax. You can use a question mark at the end of a value type to transform the type into a nullable type.

Here:We see a null int type, the HasValue and Value properties. We use the nullable type to acquire the value of the instance.

Program that uses nullable int type: C#

using System;

class Program
{
    static void Main()
    {
	//
	// Create a local variable of type nullable integer.
	// ... It is initially assigned to null.
	// ... The HasValue property is false.
	//
	int? value = null;
	Console.WriteLine(value.HasValue);
	//
	// Assign the nullable integer to a constant integer.
	// ... The HasValue property is now true.
	// ... You can access the Value property as well.
	//
	value = 1;
	Console.WriteLine(value.HasValue);
	Console.WriteLine(value.Value);
	Console.WriteLine(value);
	if (value == 1)
	{
	    Console.WriteLine("True");
	}
    }
}

Output

False
True
1
1
True
Question

Question mark suffix. The Main entry point uses a statement list in its method body that includes a local variable of type nullable int. Nullable integers are specified with the "int?" type.

Also:The int type is actually aliased to the System.Int32 type, and using "System.Int32?" would work as well.

Tip:When you use a type such as int?, you have access to extra properties such as HasValue and Value.

Programming tip

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

Also:If the HasValue property is true, you can access the Value property without an exception.

Implementation

Framework: NET

Let's examine the implementation of the nullable generic struct in the base class library. When you use a type such as int?, the C# compiler actually uses the Nullable<T> struct, where T is the value type you are using such as int.

Tip:Structs in the C# language are allocated in continuous memory for performance reasons, and this makes nullable types fairly efficient.

However:There is overhead to using nullable types and this translates to reduced performance over raw value types in some cases.

Summary

C# programming language

We looked at the nullable int type, which is specified by adding a question mark to the int type. Nullable types are described in the C# language specification as being value types that are wrapped inside the nullable type.

Also:Nullable types such as "int?" can be useful when you want to add another state (invalid or uninitialized) to a value type.


C#: Struct