The difference between .Equals (N) and == N

Possible duplicate:
== or .Equals ()

I have a String Array and just want to count the number of split lines in an array.

But I can’t decide which version I want / should / should use:

if(myStringArray.Count.Equals(47)) { // Do something. } 

or

 if(myStringArray.Count == 47) { // Do something. } 

Can someone help me figure out the difference between the two approaches and why are there both options?

I tried both and both give the same result.

+4
source share
3 answers

The Equals method provides a means for an object type to determine "equality" between two instances. Equals and == are the same thing with numbers, but when you use object types, they are different: Equals compares equality (two objects are equivalent to each other) and == compares the identifier (these are two references to the same object). The author of the class will override Equals and (usually) compares either all fields of the object with other fields of the object, or compares the key fields, depending on the class.

+6
source

In the case of structure, like the integer used here, there will be no difference. For classes maybe.

For structures like int, bool, datetime, etc. the internal value is compared with ==, not a reference. for classes == compares the reference, but equals can be overridden to apply custom comparison. for example, if the class Foo is a class that contains a primary key and overrides its basic implementation equivalent for comparing keys:

  var foo1 = new Foo{PrimaryKey = 5}; var foo2 = new Foo{PrimaryKey = 5}; foo1 == foo2 //false foo1.Equals(foo2) //true 
+1
source

Can someone help me figure out the difference between the two approaches

There is no difference in functionality, but the second is easier to read and understand, therefore it is preferable.

and why both exist?

In C #, System.Int32 is a structure, so it has an Equals(Object) method inherited from System.Object . .NET developers have also added the Equals(Int32) method, which provides an alternative with the same syntax. I have never seen Equals(Int32) , which is used in production code, simply because == easier to read.

0
source

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


All Articles