Sunday, March 15, 2015

Of Nullable Type in C#

Nullable Types (they are used for value types) are very useful when dealing with database tables that has a column with NULLABLE value type. Allowing the default value to go through in the ORM or data layer could be misleading becuase NULL could default to the 0 value say for an int type property/column.

So use int? to assign the value of the NULLABLE int column type from the database when mapping to your POCO objects. Since we use a nullable type, we can use HasValue method while mapping the property to try to get to the value.

Nullable types DONT work for reference types like strings or your reference type POCO objects, because they are already NULLABLE (default value is NULL) and the compiler does not allow it. It makes sense, because there is no reason to add NULLABLE type to reference types which are already NULL by default.

So these are not allowed
Player? nullablePlayer;
string? nullableString;


while this is allowed
int? nullableInt; //The default value then is NULL and not 0.

No comments:

Post a Comment