Using Nullable Data Types with C#
By default, the built-in base data types in C# do not allow a value of null. For instance, if you did this:
// this will not compile because int cannot be set to nullint iCount = null;
This will not compile. You will the compiler error: Cannot convert null to 'int' because it is a non-nullable value type.
In C# 2.0, Microsoft added the ability to create "nullable" types from the built-in types like int and float. To allow your int
variable to be set to null, you can use this syntax:
// this specifies int as a nullable type so it will accept null.int? iCount = null;
Another way to write this is:
// More declarative way of allowing nulls for int.System.Nullable<int> iCount = null;
I actually like this syntax better because it is easier to see what is happening at quick glance than the strange "?" syntax. You can
use this same syntax for other data types that do not allow null by default. Here are a few examples:
// More examples of making a type nullableSystem.Nullable<DateTime> dateToday = null;float? fMyFloat = null;
double? dMyFloat = null;
System.Nullable<decimal> decMyDecimal = null;
There are a couple of other caveats to remember when using nullable types.
- Datatype "string" already accepts null so there is no need to specify it as a nullable type.
- It is important to note that int? is not the same data type as int. So if you attempt to do an assignment like this:
// Will not compile. int is not the same as int?int? iMyInt1 = 0;int iMyInt2 = iMyInt1;This will not compile. You have to either cast the value like this:
// Cast int? to intint? iMyInt1 = 0;int iMyInt2 = (int)iMyInt1;
Or you can use the built in property of the System.Nullable<> template Value like this:
// Cast int? to intint? iMyInt1 = 0;int iMyInt2 = iMyInt1.Value;BE CAREFUL with the two code snippets above because if iMyInt1 was null, then casting or using its Value property would cause an
"Object not set to an instance of an object" exception. A much safer way to write this code would be:
// Safely set int? to int if int? is not nullint? iMyInt1 = 0;if (iMyInt1.HasValue){ int iMyInt2 = iMyInt1.Value;}
This uses the property "HasValue" which returns true if the value is NOT null and false otherwise.

Recent comments
13 hours 41 min ago
1 day 13 hours ago
3 days 14 hours ago
4 days 4 hours ago
4 days 14 hours ago
4 days 20 hours ago
5 days 24 min ago
1 week 21 hours ago
1 week 1 day ago
1 week 4 days ago