Comparison of equality in. Net

Source: Internet
Author: User

referential equality and value equalityin C #, equality is divided into reference equality and value equality . Reference equality refers to reference equality if a variable of two reference types refers to the same object.
//x, Y, Z are all reference type variablesObjectx =New Object();Objecty =New Object();Objectz =x;//output false,x and y do not have referential equalityConsole.WriteLine (Object. ReferenceEquals (x, y)); //output true,x and Z have referential equalityConsole.WriteLine (Object. ReferenceEquals (x, z)); //the output true,x and itself have referential equalityConsole.WriteLine (Object. ReferenceEquals (x, x));
value equality means that if two variables----can be reference types or value types----contain semantically identical values, they have value equality.
int 5 ; int 6 ; int 5 ; // output False,i and J do not have value equality Console.WriteLine (I.equals (j)); // output true,i and K have value equality Console.WriteLine (I.equals (k)); // output true,i and itself have value equality Console.WriteLine (I.equals (i));
= = and! = Operatorsthe = = operator is used to determine whether two variables are equal, and the default implementation is:
    • For reference types other than strings, determine if a variable has referential equality
    • For value types, determine if a variable has value equality
    • For string types, determine if a variable has value equality
The! = operator means the opposite of the = = operator. C # allows overloading the = = and! = operators. The rule is that to overload one of these, you must overload the other.object.referenceequals static MethodThe object.referenceequals static method is used to determine referential equality, which accepts two parameters of type Object:
int 5 ; // output False,i is boxed two times, is two different objects, does not have reference equality Console.WriteLine (Object. ReferenceEquals (i, i)); // equivalent to: object x = i; object y = i; Console.WriteLine (Object. ReferenceEquals (x, y));

In the. NET Framework's source code implementation, the ReferenceEquals method uses the = = operator to determine:

[ReliabilityContract (Consistency.willnotcorruptstate, cer.success)] [ System.Runtime.Versioning.NonVersionable]publicstaticbool  referenceequals ( Object Obja, Object objb) {    return obja = = objb;}

Code reference: http://referencesource.microsoft.com/#mscorlib/system/object.cs,4d607d6d56a93c7e

Equality of strings

In. NET, strings are reference types, but the = = operator and the Equals method use value equality to compare strings. The default comparison is case-sensitive, and sometimes we want to make a case-insensitive comparison. Therefore, the string class also has an overload of the Equals method that allows you to specify how to compare strings for equality:

 Public BOOL Equals (string value, StringComparison comparisonType)

The StringComparison parameter allows you to specify the culture, casing, and collation to use.

The example of a string indicates that equality comparisons are not absolute, two identical objects, may be equal in one context, and not equal in another context.

Object.Equals instance Methodthe signature of the Object.Equals instance method is:
 Public Virtual BOOL Equals (Object obj)

This is a virtual method, and the behavior depends on whether the override was made. The implementation of the Equals method in object returns True if the parameter obj is the same instance as the current object.

ValueType overrides the Equals method: If two value type variables have the same type, and all instance fields are equal, they have value equality. The Equals method in ValueType uses reflection implementations and has a slight impact on performance. For custom value types, consider overriding the Equals method to avoid the performance penalty caused by reflection.

Object.Equals static Method

This is a utility-type method for determining whether two variables are equal, and the method signature is:

 Public Static BOOL Equals (Object Obja, Object OBJB)
its implementation code is as follows:
 Public Static BOOL Equals (Object Obja, Object objb) {    if (obja = = objb    )        {return  True;    }     if NULL NULL )    {        returnfalse;    }     return obja.equals (OBJB);}
Analysis:1, returns True if two variables refer to the same object, or are null. 2, if any one of the variables is null and the other is not NULL, FALSE is returned. 3, if two variables are not null and the same object is not referenced, the result of Obja.equals (OBJB) is returned. overriding Object.Equals instance methods

When overriding Object.Equals instance methods, you should follow these rules:

    • Reflexive: X. Equals (x) should return True
    • Symmetry: X. Equals (y) and y.equals (x) should have the same result
    • Pass: If X.equals (y) is true and Y.equals (z) is true, then X.equals (z) should be true
    • Stable: If x and Y are not modified, then successive calls to X.equals (Y) should have the same result
    • When the argument is null, you should always return NULL.
    • If you override the Equals method, you should also override the GetHashCode method, and the GetHashCode method of two equal objects should return the same value
iequatable<t> generic interface

Iequatable<t> defines a type-specific equality comparison method, which defines only one method, signed as:

BOOL Equals (T Other)

This interface is introduced with a generic collection starting with. NET 2.0. When methods such as Contains, IndexOf, LastIndexOf, and Remove are called on a generic collection, this interface is used for equality comparisons. According to the MSDN instructions, any class that might be stored in a generic collection should implement this interface.

If you implement the IEquatable interface, you should also override the Object.Equals instance method and the Object.GetHashCode method.

iequalitycomparer<t> generic interface and Equalitycomparer<t> generic class

The IEqualityComparer declares two methods:

BOOL Equals (t x, t y) int GetHashCode (T obj)

This interface allows the Equals and GetHashCode implementations of the T itself to be skipped in a generic collection, and if an instance of iequalitycomparer<t> is provided to a generic collection, the collection uses iequalitycomparer<t The Equals and GetHashCode methods of > are compared.

Equalitycomparer<t> provides a base class for implementations of iequalitycomparer<t> generic interfaces. Equalitycomparer<t>. The default property returns the defaults for equality comparer,iequatable<t> with a generic collection that actually works here:

    • If T implements the Iequatable<t> interface, then Equalitycomparer<t>. Default uses the Iequatable<t> interface for equality comparisons
    • otherwise, equalitycomparer<t>. Default uses object.equals for equality comparisons
 

Comparison of equality in. Net

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.