How To Handle Null Values In C#

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 - the 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.

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.

Static void Main(String[] args)  
{  
   int x-null;  
   string p=null;  
}

When you 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.

Nullable<int>x=null;  
Int ?x=null; 

These are the ways to convert a non-nullable value type to a 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 the other in False. If the variable has a non-null value, then it will be set to true.

Example

static void Main(String[] args) {  
    int ? val = 10;  
    if (val.HasValue) {  
        Console.WriteLine(“contain not nullable value.”);  
    } else {  
        Console.WriteLine(“contain Null Value.”);  
    }  
    Console.Readline();  
}

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 understand this with the help of an example.

static void Main(string[] args) {  
    int ?  
        var = 10;  
    if (var.HasValue) Console.WriteLine(var.Value.ToString());  
    else Console.WriteLine(“contain Null value.”);  
    Console.ReadLine();  
}

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 the 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 the operand is not null then it returns the left-hand operand otherwise the right operand is returned by this. The Null Coalescing Operator is the binary operator that can have either True or False two values. It is used to check the null values. In case you want to assign a default value to any variable at the time when it is null, then you can use Null Coalescing Operator(??). The example is given below to explain the operator.

Class Program {  
    static void Main(string[] args) {  
        string name = null;  
        string myname = name ? ? “Jack”;  
        Console.WriteLine(myname);  
        Console.ReadLine();  
    }  
}

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 a 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 have been 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 has a null value or not. If any string is not assigned any value, then it will have a Null value. The symbol of assigning a 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 the System. String type. The method will return a Boolean value, like n case if the argument String type has a null or empty string (“), then it will return a True value else it will return a False value.

A Demo Code to Show the Use of Null Method in C#.

Input: str=null  
String.IsNullOrEmpty(str)  
Output: True  
Input: str=String.Empty  
String.IsNullOrEmpty(str)

Output

True

Here the null value is assigned to the string variable in two types, and in both cases, the output is “True” as the value is Null and when it is 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 and 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.


Similar Articles