Archive for February, 2010

C#: Nullable

The value type like int, DateTime, double can’t be null. Sometimes, you want to be able to treat value type and reference type the same way. Nullable is the answer.

Nullable n = new Nullable(3);
n.HasValue() will return true.
n.Value will return the integer 3.

You can use the ? to declare a nullable type like this:
int? n = 4;

Categories: C#

C#: is, as and cast

string s = (string)obj;

What will happen if obj is not of type string? A Exception.

You can test if obj is a string with the is keywork like this:

if ( obj is string )
string s = (stirng)obj;

A better approach is to use the as operator like this:

string s = obj as string;
if ( s != null )

The as operator will return null if the variable is not in the type requested. No exception will be generated.

Categories: C#