How to treat zeros when comparing comparisons?

When do I need to implement equality mappings for

public class SampleClass
{
    public int Prop { get; set; }
}

Should i do

null == new SampleClass() 

and

new SampleClass() == null

and

new SampleClass().Equals(null)

is false?

What about

new SampleClass() != null

Should it also be false?

UPDATE People question the arguments on this. It was assumed that! = And == would always be opposites. But if I implement methods, so all these comparisons above lead to false, there will be a case when the == and! = Operators will lead to the same result. So this is the dilemma: if! = Must return true or false.

+3
source share
8 answers

. :

new SampleClass() != null

true, , . false, , # . :

SampleClass myVar = new SampleClass();

// Various stuff happening here, possibly setting myVar to null

if (myVar != null)
{
    // Programmer go "WTFBBQ?" when he finds this doesn't get executed
    myVar.DoStuff();
}

, :

if (myVar == null)
{
    myVar = new SampleClass();
}

myVar.DoStuff(); // null reference exception, huh?
+4

? , null .

: , , new SampleClass() != null true. null NaN; .

+7

, , :

:

bool operator ==(object x, object y);
bool operator !=(object x, object y);

....

SampleClass a = null;
SampleClass b = null;
  • a == b
  • a!= b - false

, .NET :

"bool?" "bool" ?

:

+2

, , null ( ) . ,

null == new SampleClass()

(, , ).

?

+1

, null , null. , null , .

, , , , . , , , .

+1

. != true, .

+1

, , .

0

, . , , , .

, null .NET , null , .

SQL, , 1 = null 1 <> null null, null , null , null, - .

# null , , , null .NET.

null , , , .

" ".

" , - " " , ", " , " .. , . ( , ", , , " ).

, , , , , , . :

  • , null , .

  • , x == y x != y x y, .

:

  • , , .

  • x != null x == null.

, .NET 2.0 , : Nullable<T> ( T? #). , ( - , , : x == null true, (object)x == null false.

, Nullable<T> , , , , Equals(), true null.

0

Source: https://habr.com/ru/post/1715468/


All Articles