Nullable .Net types
We declare .net types in our project daily but still we do not recollect default values for each .net type so we end up doing null check for each data type. Its a basic mistake of a developer but .net makes us intelligent with one of their operator, ‘?’
Nullable is represented by a ‘?’.
Prior to that, uninitialized variables in C# is not allowed so we should know default values of .net datatypes.
For value types, mostly it is 0. For ex:
I have specified only the basic value types which we use in our daily development work. For detailed list for value type, click here.
|Value type||Default value|
|struct||The value produced by setting all value-type fields to their default values and all reference-type fields to null.|
For reference type, default value is null.
Now, the condition we normally see is to have default value as ‘Null’ for value type. To achieve this we have nullable operator ‘?’ which we mentioned earlier. How to use it?
Just put it in front of your value type variable. For ex:
This will make int variable accept ‘Null’. Please note this one more important information, if we have one int variable and other nullable int variable then they are not equivalent and cannot be assigned to each other. For ex:
x=y; — It is not possible and will throw compile time error.
To correct it, Both the variables should be nullable.
Nullable has two more properties. ‘HasValue’ for a null condition check and ‘Value’ to get the actual value.
We sometimes fail to differentiate between the uses of ‘?’ as it can be used in many ways.To avoid the confusion regarding ‘?’. One of the use is a conditional operator. For ex:
int id = x > y ? x : y;
it is same as -
if( x > y )
Same kind of operation can be written with ‘??’ but only for null check.
int? y= x?? 1;
This exercise requires some real time practice and will be much more clear so I request you all to try it and send your feedback. .