Check if an object is null in C#
This post will discuss how to check if an object is null in C#.
There are several ways to check if an object is null in C#:
1. ‘is’ constant pattern
Starting with C# 7.0, the is operator supports testing an expression against a pattern. The null keyword is supported by the is statement. We can check the null using the constant pattern. The following example shows its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { String ob = null; if (ob is null) { Console.WriteLine("Object is null"); } else { Console.WriteLine("Object is not null"); } } } |
2. Equality operator (==)
Another standard way to check for the null object in C# is to use the equality operator (==). This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { String ob = null; if (ob == null) { Console.WriteLine("Object is null"); } else { Console.WriteLine("Object is not null"); } } } |
3. Using Object.ReferenceEquals method
The Object.ReferenceEquals() method determines whether the specified Object instances are the same instance. It returns true if both object instances are null.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { String ob = null; if (object.ReferenceEquals(null, ob)) { Console.WriteLine("Object is null"); } else { Console.WriteLine("Object is not null"); } } } |
That’s all about determining whether an object is null in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)