-1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.