How many ways are there to check if an object is null? RRS feed

  • Question

  • User1884398186 posted

    The most traditional way of checking if an object is null is :  if ( object == null)

    Can I also use : if ( object is null)? If yes, then which is more efficient OR is there another better way of doing this?

    Monday, November 27, 2006 8:11 PM

All replies

  • User300685930 posted
    In C#, I always use String.IsNullOrEmpty to figure out if a string is empty.  Otherwise, I think == is the best way to do it.
    Monday, November 27, 2006 8:30 PM
  • User1884398186 posted

    But the String.IsNullOrEmpty is only for 'string'.

    I was asking a question about an object, which could be of any type.

    For example, if 'employee' was of type 'Employee', then could I use if (employee is null) or if (employee ==  null)  and which one would be the best from performance point of view?

    Monday, November 27, 2006 9:08 PM
  • User-1630302068 posted
    From a performance point of view neither of them is doing anything which is operationally excessive so they're equivalent in your Big-O analysis.  If you're not doing your Big-O optimization on your algorithms than any performance questions other than DB optimization is simply putting the cart before the horse.
    Tuesday, November 28, 2006 9:37 AM
  • User397347636 posted

    You must use "if (object == null)". 

    "object is null" won't even compile.  The C# "is" operator is strictly for type checking, not identity comparisons.


    Tuesday, November 28, 2006 10:36 AM
  • User1192250343 posted

    if (object == null)

    will give an error in SonarQube code quality review like 

    Change this condition so that it does not always evaluate to 'false'; some subsequent code is never executed.

    Friday, March 16, 2018 6:32 AM