nullable types

T

Tony Johansson

Hello!

These two declarations(1 and 2) are the same I assume.
1. System.Nullable<int> nullable;
2. System.Nullable<int> nullable = new System.Nullable<int> ();

So because these 1 and 2 are the same is no point to use the longer
declaration as 2 it good enough
to use decaration 1.

Do you agree with me?
The declaration of nullable above a value type or a reference type?

//Tony
 
K

KH

The first one can't be used until it is assigned a value, so

Nullable<int> nullable;
Console.WriteLine( nullable.HasValue ); // Compiler error here

Nullable<int> nullable = new Nullable<int>();
Console.WriteLine( nullable.HasValue ); // OK

You can also use the ? shorthand in C# for nullable types:

int? nullable = null; // same as second example above

HTH
 
J

Jon Skeet [C# MVP]

Tony Johansson said:
These two declarations(1 and 2) are the same I assume.
1. System.Nullable<int> nullable;
2. System.Nullable<int> nullable = new System.Nullable<int> ();

Not for local variables. A local variable declared as per 1 has no
definitely assigned value. In other words, this won't compile:

void Invalid()
{
System.Nullable<int> nullable;
if (nullable == null)
{
Console.WriteLine("Null");
}
}

whereas this will:

void Valid()
{
System.Nullable<int> nullable = new System.Nullable<int>;
if (nullable == null)
{
Console.WriteLine("Null");
}
}
So because these 1 and 2 are the same is no point to use the longer
declaration as 2 it good enough
to use decaration 1.

Well, I'd generally use:

int? nullable;
or
int? nullable = null;

The latter is potentially slightly clearer to readers.
Do you agree with me?
The declaration of nullable above a value type or a reference type?

A nullable value type is still a value type. When the null literal is
used (as above) with a nullable value type, it represents the "null
value" of the type, which is the value where HasValue returns false.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top