C# 2.0 Features - Part 2.7 Nullable types

Sep
02
2010
In Categories: .NET | CLR
Tags | |

You can see part 1 here, part 2.1 here, part 2.2 here, part 2.3 here, part 2.4 here, part 2.5 here and part 2.6 here.

This feature solves a lot of problems and eliminates some logic we get used to write. Before Nullable types we get used to set the value types variable that are loaded from the database to Minimum value to represent that the Database has null value. Know after framework 2.0 goodbye this work around. We simply use ? operator after the type to represent that this type can accept null. Let's see an example to show how can we declare and use it.

    1    int? x;

    2    x = 10;

    3    if (x.HasValue)

    4        Console.WriteLine(x.Value);

    5    x = null;

    6    Console.WriteLine(x + 10);

    7    int y = x + 10;

    8    int y = x.Value + 10;

As we can see here, we have placed "?" after the data type. Setting the value can be normally done. We have checked if the variable has value or not. We can also assign the variable to null. If we do like we did in line 6 while the nullable type is null there will not be an exception raised and the result will be null also. Line number 7 will generate compilation error as we can't assign int? to int. Line number 8 will generate InvalidOperationException. It is a good feature but use it with care.

Comments

trackback
Technical Architect blog
9/5/2010 5:48:27 AM Permalink

C# 2.0 Features - Part 2.8 Null-Coalescing Operator

C# 2.0 Features - Part 2.8 Null-Coalescing Operator

Comments are closed