简体   繁体   中英

C# ignores null check?

Who can explain to me this irrational lame beauty of C# logic in blazor-server?

在此处输入图像描述

What is club , and does it perhaps have a static == operator overload that is not null-safe? For example, the following is possible and broken:

bool == (Foo x, Foo y) => x.Id == y.Id;

It is broken because it doesn't consider that x and/or y could be null . Using club == null will call this broken operator, causing a NRE.

A good way to check is to use club is object instead of club != null , as the is object / is null syntax never calls static == operator overloads.

Maybe You should compare club to null like this:

if (!(club is null) && club.Id > 0)

I think NullReferenceException is caused by == operator, which can use methods that are not "null safe".

To ensure the reference is null you can use:

ReferenceEquals(myObject, null)

It is a static method from the Object class itself so basically it can be used everywhere.

Most of the time it will give you the same result as:

myObject == null

But since the "==" can be overloaded you can have strange behavior. See operator overload .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM