Comparing values โ€‹โ€‹using the == operator

I have a static method that simply compares two values โ€‹โ€‹and returns the result

public class Calculator { public static bool AreEqual(object value1, object value2) { return value1 == value2; } } bool Equal = Calculator.AreEqual("a", "a"); // returns true bool Equal = Calculator.AreEqual(1, 1); // returns false 

Can someone explain what happens behind the scenes that produce the above conclusion

-1
source share
1 answer

The runtime identifies your literary uses of "a" and returns the same reference to all of these usages, resulting in one string object, not two as you expected.

Instead of using literals, try the following:

 string A1 = new string(new char[] {'a'}); string A2 = new string(new char[] {'a'}); Calculator.AreEqual(A1, A2); // returns false 

What you have presented here is known as string interning.
Further information can be found on the String.Intern page.

+1
source

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


All Articles