Bad Practice to use Nullable<T> with Value Types?

What should be the preference? A default value of a value type (i.e. int SomeConfigOption = -1;) or utilizing Nullable (i.e. int? SomeConfigOption;)?

In this case clearly you want Nullable<T> whenever you have the case that you have to account for the absence of a value. Magic numbers like -1 are a far worse maintenance nightmare.

This is a core feature of the C# language, as with other features it can be abused but it provides clear benefits as well - these benefits far outweigh any problems someone not proficient in the language might have reading the source code - time to get up to speed.


I think Nullable looks nice: code with Nullable types is quite self-documented.

Examples:

int? someConfigOption;
if (someConfigOption.HasValue)
{
    // Use someConfigOption.Value property.
}
else
{
    // Value is absent.
}

Another handy approach:

int value = someConfigOption.GetValueOrDefault();

Of course, the methods which take Nullable values as their parameters should be well documented.

Tags:

C#