C# Programming Guide
Nullable Types (C# Programming Guide)

Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true or false, or null. The ability to assign null to numeric and Boolean types is particularly useful when dealing with databases and other data types containing elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

C#
class NullableExample
{
    static void Main()
    {
        int? num = null;
        if (num.HasValue == true)
        {
            System.Console.WriteLine("num = " + num.Value);
        }
        else
        {
            System.Console.WriteLine("num = Null");
        }

        //y is set to zero
        int y = num.GetValueOrDefault();

        // num.Value throws an InvalidOperationException if num.HasValue is false
        try
        {
            y = num.Value;
        }
        catch (System.InvalidOperationException e)
        {
            System.Console.WriteLine(e.Message);
        }
    }
}

The above will display the output:

num = Null

Nullable object must have a value.

Nullable Types Overview

Nullable types have the following characteristics:

  • Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

  • The syntax T? is shorthand for System.Nullable<T>, where T is a value type. The two forms are interchangeable.

  • Assign a value to a nullable type in the same way as for an ordinary value type, for example int? x = 10; or double? d = 4.108;

  • Use the System.Nullable.GetValueOrDefault property to return either the assigned value, or the default value for the underlying type if the value is null, for example int j = x.GetValueOrDefault();

  • Use the HasValue and Value read-only properties to test for null and retrieve the value, for example if(x.HasValue) j = x.Value;

    • The HasValue property returns true if the variable contains a value, or false if it is null.

    • The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.

    • The default value for a nullable type variable sets HasValue to false. The Value is undefined.

  • Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;

  • Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;

Related Sections

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 24 Nullable Types

See Also

Tags :


Community Content

joniba
Problem with nullable types and conditional expression

I having a problem passing values to a dataAccess method with nullable types. I need to pass nulls if there is no value.

But this:

DataTable dt =
DataAccess.DoSomething
(
from,
to,
aIdNullable.HasValue ? aIdNullable.Value : null,
bIdNullable.Value ? bIdNullable.Value : null,
cIdNullable.Value ? cIdNullable.Value : null
);

gives this error:

"Type of conditional expression cannot be determined because there is no explicit conversion between 'long' and '<null>'"

Is there a solution to this?

Tags : types nullable

Damjan Tomic
Re: Problem with nullable types and conditional expression
You should try something like this:
DataTable dt =
DataAccess.DoSomething
(
from,
to,
aIdNullable,
bIdNullable,
cIdNullable
);
instead of trying to pass aIdNullable.Value which is variable of type long (as can be seen from the error)
Tags :

daras
Error with nullable types and conditional expression
Similar to above problem.

int? x;

x = 0;
x = null;
x = true ? 0 : null; // This line throws error below

Error 12 Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'

x = true? 0 : (int?) null;


daras
try x = true?0:(int?)null;
try x = true?0:(int?)null;
Tags :

doNotMug
Drawbacks of using nullable types?

Are there any drawbacks? i have a small class

class product{
int? quantity; string? brand; double? price;
}

product p = new product();
if (p.quantity !=null)...; if(p.brand !=null)...; if(p.price !=null)



would it be better (faster, more robust) to do the following:

class product{
int quantity=-1; string brand; double price =-1.0;
}

product p = new product();
if (p.quantity >0)...; if(p.brand.length >0)...; if(p.price >0)



For example i have read that brand.length is faster than than brand !="". Also to think of assigning a default value in case of assigning a nullable type (x = null; int y = x ?? -1;) makes me shiver.

Any ideas pointers







Page view tracker