Whidbey's Nullable<T> template

One of the new templates added in Whidbey's BCL is Nullable, which allows defining Nullable providing "nullness" on value types. The usage is very simple:

Nullable oi = null;
Console.WriteLine( oi.HasValue ); // false
Console.WriteLine( oi == null ); // true
oi = 3;
Console.WriteLine( oi.HasValue ); // true
Console.WriteLine( oi == null ); // false

The instance can be null because it's a reference type and the assignment can be done because operators are also specialized for type T.

I don't want to talk about the difference between ValueTypes and ReferenceTypes, or if the performance of the Nullable instances can be compared with the ValueTypes usage. But i was wondering about its usage in applications and probably their usage could be a bit complicated.

Any method that wanted to receive any value will receive an object:

void MyMethod( object t ){}

In the method body any one will query if the value is a ValueType or a ReferenceType. Now we have to ask for the instance to see if it's an Nullable<> instance. But what is the template implementation that will be used to query using the "is" keyword, there's no way to use the template as an abstract base class, so we can't know what is the type without using Reflection.

I have some solution for this. If the Nullable is declared using an interface defining the property HasValue, we can solve the problem because any template implementation will also implement the interface and "is" can be used to query the type of the reference.

public interface INullable
bool HasValue{ get; set; }
public class Nullable : IINullable
   // implementation

No Comments