Nullable Types in C#

5/24/2004 6:24:22 PM

Nullable Types in C#

The updated C# 2.0 specification has been released. It looks like C# has gained another significant feature, extended syntax and support for nullable types.

To refer to a nullable type, the base value type T needs to be followed by a question mark, which is shorthand for Nullable. Nullable types have just two methods, Value and HasValue.

int? var = 1; 

Nullable types can be assigned and compared to the value, null.

var == null

Nullable types can be implicitly and explicitly converted to and from the base type. There is a safe (non-throwing) conversion operator, ??, that provides for a default value if the nullable variable is null.

var ?? 1

Nullable types also support all the native unary and binary operators of their underlying type, returning a null if any of the operands are also null, or, in the case of comparison operators, returning false.

There is special treatment for booleans. Nullable bools are a form of ternary boolean values, which can safely be used in if, for, while conditions and logical expressions without throwing exceptions.

The specification makes no mention of other features that currently exists in the Community Technology Preview, such as fixed arrays.

Comments

 

Navigation

Categories

About

Net Undocumented is a blog about the internals of .NET including Xamarin implementations. Other topics include managed and web languages (C#, C++, Javascript), computer science theory, software engineering and software entrepreneurship.

Social Media