Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coding practices for C# Nullable type [closed]

Tags:

I have never used nullable types in my C# code. Now I have decided to change my coding practice by introducing nullable types in my code.

What are the major changes in the coding practices should be made while making a transition from normal datatypes to nullable data-types in case of application programming?

What are the areas that should be taken care of?

What are the points I should always watch out for?

like image 229
user366312 Avatar asked Oct 11 '09 15:10

user366312


2 Answers

Don't use nullable types because they are a "cool new thing" you have discovered. Use them where they are applicable and genuinely useful.

There are overheads to using them, and if used incorrectly they will unnecessarily increase the complexity of your code.

You also have to be careful to avoid null dereferences, so they place additonal burden on programmers working with that code. (In some cases this is preferable to the cost of a workaround approach though!)

like image 138
Jason Williams Avatar answered Sep 28 '22 12:09

Jason Williams


Nullable<T> is useful for when you need a possible invalid state for a value type, or if the data is being retrieved from a database that may contain a null value for the column. It is very common in some old FORTRAN code I am porting to C# for invalid values to be negative or 0, but this is troublesome especially when the values are used in mathematical functions. It is far more explicit to use Nullable<T> to show that possible invalid state.

It is worth mentioning that the following is the same:

Nullable<int> myNullableInt; int? myNullableInt; 
like image 35
user7116 Avatar answered Sep 28 '22 11:09

user7116