Limitations of the = = operator in C #

Source: Internet
Author: User

The = = operator is popular for its simplicity of syntax, but it also has limitations, such as inheritance or generic problems. Let's take a look at it in turn.

1. = = and the question of inheritance

For an example of an issue where the = = operator is inherited, we describe it as a string type.

static void Main (string[] args)        {            string str = "Hello";            String str1 = String. Copy (str);            Console.WriteLine (ReferenceEquals (str, str1));            Console.WriteLine (str. Equals (STR1));            Console.WriteLine (str = = str1);            Console.WriteLine (object. Equals (str, str1));            Console.read ();        }

Run the above code, which in turn produces: False, True, true, true. The results are easy to explain, except for the comparison of ReferenceEquals methods, the other three comparison methods are value comparisons.

Now let's modify the above code a little bit, as follows:

static void Main (string[] args)        {            Object str = "Hello";            Object str1 = string. Copy (str);            Console.WriteLine (ReferenceEquals (str, str1));            Console.WriteLine (str. Equals (STR1));            Console.WriteLine (str = = str1);            Console.WriteLine (object. Equals (str, str1));            Console.read ();        }

Run the above code again, with the result: false, True, False, true. Compared with the above results, it can be found that only the = = Operator's result has changed, this is why?

The reason is that = = is equivalent to a static method, and the static method cannot be virtual, in this case, when compared with = =, compared with two variables of type object, although we know that Str and str1 are actually string type, but the compiler is not aware of this. One thing we should keep in mind is that for calls of non-virtual methods, the specific invocation of which implementation was made at compile time has been decided. Specifically to our example, that is, we declare two variables of type Object str and STR1, then the compiler generates code that compares object types. The object class is implemented with overloaded versions that do not have the = = operator, so = = will compare referential equality, which returns false because Str and STR1 are two different instance objects.

In the face of the inability to inherit, we should not choose = =, but should use the Equals method for the award. Next look at how the Equals method solves the problem.

Obviously, when the Equals method is used for testing, no matter what is called Str. Equals is also the Object.Equals method, and the final invocation is the implementation of the override version of the string type, so we can always calculate the expected results. Therefore, when there is an inheritance problem, you should use the Equals method for sentencing, instead of the = = operator.

  Finally, as you can see from this example, when we move the operand of the = = operator to the object type, it will conduct a reference equality test, always consistent with the referenceequals result, so some developers use this method to compare reference equality. But one drawback of this is that other developers may have doubts when reading such snippets. Therefore, it is best to always use the ReferenceEquals method when comparing reference equality.

2, = = and generic issues

Another drawback of = = is the inability to work well with generics. Consider the following code:

static void Equals<t> (t A, T b) {    Console.WriteLine (a = = B);}

The logic of the above code is simple, which is to use = = to compare two objects of type T. But compiling the above code will make an error:

The above error is reported because T may represent any type, including primitive types, value types, and reference types. It is not possible to determine whether the passed type implements the = = operator overload.

In C #, for generic types, we cannot impose a constraint that requires an overload of the passed-in generic type T to implement = =.

Now that we can build code, the only problem is that equals is limited to accepting reference types, not value types.

Now, let's take the example of a previous string comparison,

Class program{    static void Main (string[] args)    {        Object str = "Hello";        Object str1 = string. Copy ((string) str);        Equals (str, str1);    }    static void Equals<t> (t A, T b) where T:class    {        Console.WriteLine (a = = b);}    }

Now, guess what the output of the above code is, true or false? If we recall that the string type defines the overloaded implementation of the = = operator, it is possible to guess that the result of the above code is true, but the actual run result shows false. At this point the intuitive guess is that the = = operator calculates the citation, not the value of the sentence. Let's see what's going on here.

In the above code, although the compiler knows through the where T:class statement that it can use the = = Operator for any incoming type of test, corresponding to this example, T is the string type, and the string type provides the overloaded implementation of = =. However, the compiler does not know whether the generic type T overloads the = = operator, so it assumes that T does not overload = =. When the compiler compiles code, it is assumed that the object base class = = operator is called, so the = = operator is tested for referential judgment.

  One thing to keep in mind: when using the = = operator on generic type T, the compiler does not use the = = operator overload defined by type T, instead it treats t as the type of object and invokes the = = Operator method of the object base class.

Next, let's look at how the Equals method solves the problem above.

static void Equals<t> (t A, T b) {   Console.WriteLine (object). Equals (A, b));}

As you can see, we removed the class-qualified statement for the generic method, because the Object.Equals method can be called on any type, and the static qualification is used to avoid null for the instance object that makes the call, and it is clear that the generic method above works on both the value type and the reference type.

We run the above code again, and the result shows true. This is because the Object.Equals method calls its override version implementation at run time, in this case the definition of the override implementation is in the string type, and the implementation carries out a value-based test.

Limitations of the = = operator in C #

Related Article

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.