-1

I am developing an application in .NET Core 7.0. See the code block below shows the condition that works and the one that doesn't.

Please suggest why is it happening?

Thanks.

Update:

Here is the code snippet.

        User dbUser = databaseUsers.FirstOrDefault(x => x.Key == user.ObjectGuid).Value;
        if (dbUser != null)
        {
            // Handle user when it' null
        }

The databaseUsers is a SortedDictionary<string, User>. When the dbUser null it still go inside the if condition and only behave correctly when i change the condition to "dbUser is not null".

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Imran Yaseen
  • 543
  • 1
  • 5
  • 20
  • 2
    Hi, could you provide more details? What does it mean 'doesn't work'? – Marek Koziorowski Feb 02 '23 at 08:59
  • 1
    Visual Studio is just the editor, not the language. `user != null` works just fine. Post actual code (not images) that reproduce the problem. Images can't be copied, compiled, tested or googled. – Panagiotis Kanavos Feb 02 '23 at 09:01
  • 1
    Could you please include example code (as text within the question) that demonstrates the issue. Please also explain what doesn't work. – phuzi Feb 02 '23 at 09:01
  • 1
    My quess?: `User` has an operator overload that doesn't handle null correctly. Using pattern matching does not call operators declared in that class. – Sebastian Schumann Feb 02 '23 at 09:01
  • 1
    If what you claim was true hundreds of thousands of developers would notice because **all** C# programs would break. Something strange is going on either with `User` or `GetByIdAsync` – Panagiotis Kanavos Feb 02 '23 at 09:01
  • Please check if this post will help you https://stackoverflow.com/questions/40676426/what-is-the-difference-between-x-is-null-and-x-null – Marek Koziorowski Feb 02 '23 at 09:02

1 Answers1

4

Please provide more info.

The difference between != and is not null is that != can be overridden.

That means that you can change is behavior. As you can see in these docs

Your != has probably been overridden in User class

BorisD
  • 1,611
  • 17
  • 22