• API
    • CPF
  • Blog
  • Contact

Contact Us

Give us a call or fill in the form below and we will contact you. We endeavor to answer all inquiries within 24 hours on business days.

Edit Content

     

    Technology

    Understanding obj == null vs obj is null in C# and Their Performance Impact

    January 30, 2025 Bruno de Souza Melo, Weslei Gomes de Sousa

    When working with null checks in C#, developers often use one of the following approaches:

    if (obj == null) { /* do something */ }
    if (obj is null) { /* do something */ }
    

    Both methods check if an object reference is null, but there are important differences between them, especially regarding operator overloading, reliability, and performance.

    In this article, we will explore these differences and analyze their performance impact.


    1. The Equality Operator (obj == null)

    The statement:

    if (obj == null)
    

    uses the equality operator (==) to compare obj to null.

    How it Works

    • For reference types, == checks if obj refers to null in memory.
    • For value types, == typically checks for equality rather than null (unless nullable types are involved).
    • Custom classes can override operator ==, which might lead to unexpected behavior.

    Example of an Overloaded == Operator

    Consider the following custom class:

    class MyClass
    {
        public static bool operator ==(MyClass a, MyClass b)
        {
            return false; // Always returns false, even if null!
        }
    
        public static bool operator !=(MyClass a, MyClass b)
        {
            return true;
        }
    }
    

    Now, let’s test it:

    MyClass obj = null;
    
    if (obj == null)
    {
        Console.WriteLine("obj is null");
    }
    else
    {
        Console.WriteLine("obj is NOT null");
    }
    

    Expected Output? You might think "obj is null" will be printed, but due to the overloaded == operator, it will actually print:

    obj is NOT null
    

    This demonstrates why obj == null may not always work as expected in custom classes.


    2. The Pattern Matching Approach (obj is null)

    Introduced in C# 7.0, the is keyword provides a more reliable way to check for null:

    if (obj is null)
    

    Why is is null More Reliable?

    • It cannot be overridden, making it safe from custom == overloads.
    • It uses pattern matching, which is optimized for null checks.

    Let’s revisit the overloaded operator example:

    if (obj is null)
    {
        Console.WriteLine("obj is null");
    }
    

    Regardless of the overloaded == operator, this will always print:

    obj is null
    

    Thus, obj is null guarantees accurate null checks, even in custom types.


    3. Performance Comparison

    While obj is null is safer, does it have a performance cost? Let’s analyze.

    IL Code Comparison

    C# code is compiled into Intermediate Language (IL). Let’s see how both checks translate:

    For obj == null

    if (obj == null) { /* do something */ }
    

    The IL generated:

    ldloc.0     // Load obj
    ldnull      // Load null
    ceq         // Compare equality
    

    For obj is null

    if (obj is null) { /* do something */ }
    

    The IL generated:

    ldloc.0     // Load obj
    ldnull      // Load null
    ceq         // Compare equality
    

    Result: No Performance Difference

    Both approaches generate the same IL code, meaning there is no performance penalty for using is null.

    However, since is null is safer (immune to overloaded operators), it is generally the preferred approach.


    4. Best Practices: When to Use Which?

    ApproachCan Be Overridden?Safe for All Cases?Performance Concern?
    obj == null✅ Yes⚠️ No (if == is overloaded)❌ No
    obj is null❌ No✅ Yes (Always safe)❌ No

    ✅ Use obj is null when:

    • Working with custom classes that may overload ==.
    • Ensuring absolute reliability in null checks.

    ✅ Use obj == null when:

    • Working with simple reference types that do not override ==.
    • Codebases that predate C# 7.0 and lack is null.

    5. Conclusion

    Both obj == null and obj is null perform equally well, but obj is null is safer due to its immunity to overloaded operators.

    If you’re working with modern C# (7.0 and later), it is recommended to always use is null for null checks to avoid unexpected behavior.

    • Bruno de Souza Melo

      Over 20 years of experience delivering innovative IT solutions for public and private sectors, enhancing user welfare and societal impact.

      Expertise
      Development & Infrastructure: Extensive experience with Visual Studio (2003–2022), Azure, GCP, AWS, messaging platforms (Azure Service Bus, Pub/Sub, RabbitMQ), Azure DevOps (CI/CD, Git, Artifacts), Docker, Microsoft 365, SharePoint, IntelliJ IDEA, and more.
      Data Tools: Proficiency in Spark, Jupyter/Zeppelin, and Hue for Impala/Hive (HDFS). Databases: Skilled in Microsoft SQL Server, PostgreSQL, MongoDB, Oracle, and others.
      Technologies & Languages: Expertise in web development (Blazor, React, Angular, Razor Pages), TypeScript, Python, ASP.NET Web API, Xamarin, Entity Framework Core, C#, Java/Spring, and Windows applications (WPF, WinForms, UWP).

      Methodologies & Architecture
      Agile methodologies (Scrum, Kanban) for efficient project management. Solution architecture, including business modeling (BPMN, C4 Model) and technology frameworks (Clean Architecture).

      Industry Experience
      Diverse domain knowledge across fast food, transportation, banking, hospitality, contracts, and more.

    • Weslei Gomes de Sousa

      With over 20 years of experience in IT solutions architecture, has strong expertise in .NET and Azure and high proficiency in managing relational and non-relational databases. Techs: Azure Architecture, Azure DevOps (CI/CD, Artifacts, Git), Docker, Azure Storage, B2C, Azure Service Bus, RabbitMQ, AWS Cloud, Web Applications/Frontend (Angular, Blazor, React, Razor Pages), TypeScript, Python, ASP.NET Web API (REST), MAUI (Mobile Development), Entity Framework Core, C#, Windows Applications (WPF, WinForms, UWP), Java, among others.

    Post navigation

    Previous
    Next

    Search

    Categories

    • Technology (7)

    Recent posts

    • State Management in Blazor: Best Practices and Strategies
    • Understanding obj == null vs obj is null in C# and Their Performance Impact
    • 500x Faster: Avoid Queries in Loops with C# Entity Framework for Peak Performance

    Tags

    #ai #artificialintelligence #judiciary #speedtrial #ai #artificialintelligence #publicsector BestPractices Blazor c# CleanCode converter CSharp dataperformance datetime DotNet ef entity entityframework enum highperformance json keys nuvtools nuvtools.common serialization Web

    Related posts

    Technology

    State Management in Blazor: Best Practices and Strategies

    March 3, 2025 Weslei Gomes de Sousa, Bruno de Souza Melo

    State management is a critical aspect of building Blazor applications, as it determines how data is stored, updated, and shared across components. Unlike JavaScript frameworks such as React and Angular, Blazor leverages C# for managing state, offering several built-in and advanced strategies. This article explores state management approaches in Blazor, covering built-in options and external […]

    Fuel your business growth and witness immediate results today.

    Menu
    • Home
    • API
    • Blog
    • Contact

    © Nuv Tools Technology. All Rights Reserved.

    © Nuv Tools Technology.
    All Rights Reserved.