Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a static method which 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 please explain what is going on behind the scenes that produces the output described above

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
135 views
Welcome To Ask or Share your Answers For Others

1 Answer

The runtime identifies your literal usages of "a" and retrieves the same reference to all those usages, resulting in one string object rather than two as you would expect.

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've presented here is known as string interning.
You can find more information in the String.Intern method page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...