How To Handle Null Values In C#

In this article, you will learn what null values are and how to handle null values in C#.

Today, in this post, we are going to discuss the Nullable type of C#. In C#, NULL values are treated in a special manner which is already defined in the language. C# data types are divided into two categories - first is Value Type, and the other is Reference Type. If you have ever considered a value type variable, then it can never be assigned a NULL value, but the developers of C# can assign a NULL value to any Reference type variables.
 
Today, we will see the use of NULL values with the help of examples. One other term that we will discuss here is NULL-Collation.
 
Moreover, if you want to check the NULL value, then you can also use a pre-defined method that is known as IsNullOrEmpty(). So, let us start our discussion for handling NULL values in C#.
 

Use of NULL Values in C#

 
Let us start our discussion with an example where we will assign a NULL value to a value type variable,
  1. Static void Main(String[] args)  
  2. {  
  3.    int x-null;  
  4.    string p=null;  
  5. }  
When you will assign a NULL value to a variable and execute this program, then it will throw an error saying “Cannot convert null to ‘int’ because it is a non-nullable value type.” Coders can see such errors many times while coding. This problem can be solved in the following two ways,
  1. Nullable<int>x=null;  
  2. Int ?x=null;  
These are the ways to convert a non-nullable value type to nullable value type in C#. Any type is known as nullable if you can assign a value or null to this variable it means that the type will have no value. In C# all reference types like string are of a nullable type, but the other types like int32 are not nullable type. A nullable type has two members,
  1. HasValue
  2. Value
HasValue is a Boolean type value that can again have two types of values one in True and other is False. If the variable has a non-null value, then it will be set to true.
 
Example
  1. static void Main(String[] args) {  
  2.     int ? val = 10;  
  3.     if (val.HasValue) {  
  4.         Console.WriteLine(“contain not nullable value.”);  
  5.     } else {  
  6.         Console.WriteLine(“contain Null Value.”);  
  7.     }  
  8.     Console.Readline();  
  9. }  
Here the output will contain a nun-nullable value.
 
Value is of Boolean type. The variable value contains the data stored in the nullable type. Let us understood this with the help of an example,
  1. static void Main(string[] args) {  
  2.     int ?  
  3.         var = 10;  
  4.     if (var.HasValue) Console.WriteLine(var.Value.ToString());  
  5.     else Console.WriteLine(“contain Null value.”);  
  6.     Console.ReadLine();  
  7. }  
The output of the above code fragment will be – 10. So in this way, the Null values are handled in C#. Now we will see one other important term associated with Null types, and that is Null-Collation in the next section of this post.
 

Null-Collation

 
In C# there is another operator defined in MSDN and is known as Null-Collation operator (??). It is known as the null-coalescing operator that is used to define the default value for nullable reference or value types. In case if the operand is not null then it returns left-hand operand otherwise the right operand is returned by this. The Null Coalescing Operator is the binary operator that can have either True of False two values. It is used to check the null values. In case if you want to assign a default value to any variable the time when it is null, then you can use Null Coalescing Operator(??). The example is given below to explain the operator,
  1. Class Program {  
  2.     static void Main(string[] args) {  
  3.         string name = null;  
  4.         string myname = name ? ? “Jack”;  
  5.         Console.WriteLine(myname);  
  6.         Console.ReadLine();  
  7.     }  
  8. }  
  9. `  
Output
 
Jack
 
Here the output is Jack, as initially, the variable name has a null value and the operator checks for a NULL value, and if it has Null value, then the default value will be assigned to the variable or the left-hand side value.
 

IsNullOrEmpty() Method of C#

 
Well, so far we were discussing the value types that can have either null or not-null values. Now, as we are discussing Null values of C#, so one other concept that is associated with Null values is the method named IsNullOrEmpty(). This method is used when you want to check whether the given string is Empty or have a null value or not? If any string is not assigned any value, then it will have Null value. The symbol of assigning Null value is “ “or String.Empty(A constant for empty strings).
 
Syntax
 
public static bool IsNullOrEmpty(String str)
 
This method will take a parameter that will be of System. String type. The method will return a Boolean value, like n case if the argument String type has null or empty string (“”), then it will return True value else it will return False value.
 
A Demo Code to Show the Use of Null Method in C#, 
  1. Input: str=null  
  2. String.IsNullOrEmpty(str)  
  3. Output: True  
  4. Input: str=String.Empty  
  5. String.IsNullOrEmpty(str)  
Output
 
True
 
Here the null value is assigned to the string variable in two types, and in both the cases the output is “True” as the value is Null and when it will be checked it will return True. We can also understand the Null value method by taking more examples.
 
It would not be wrong to say that Null values are equally important and cannot be overlooked in any programming language, and this is so in C# as well. Here the Null values can be treated in many ways, and they are just a few cases of them.
 

Conclusion

 
In C# Null values, Null coalescing and IsNullOrEmpty methods are used for three various purposes and cases. In this post, we discussed in detail about these keywords of C#. However, Null Coalescing has certain advantages and disadvantages as well as if it is incorporated inside the code then it can decrease the number of lines of the code. Though it cannot improve the performance of speed of the program but can optimize the code. As a result, the code becomes easier to understand.