Possible Duplicate:
Differences in string compare methods in C#
I know that in C# strings are objects, and I just learned about the CompareTo method when comparing two strings. But what if I need to compare the string to a specific text value?
Now I’m doing this:
private string choice;
[...some code...]
if (choice == "1")
{
Console.WriteLine("You choose 1");
Console.ReadLine();
}
else if (choice == "2")
{
Console.WriteLine("You choose 2");
Console.ReadLine();
}
etc...
And it works just as I want. But is it good coding? Can not find any information on this specific topic.
You can safely compare a string reference to a string literal.
There are some edge cases where the compile time matters
In the forst three lines is a value comparison and as long as the value of the string object is the same the result will be true.
In the last three lines it’s a reference comparison, because the compile time type of the variables are object.
a and b are going to be the same object so the first comparison will return true. however oa and oc are not going to be the same object. There’s no way for the compiler to determine that they are actually the same string value. The last line will also return true. This is because the compiler will realize at compile time that a and d has the same string value and will therefor only create one string object. It can safely do this because strings are immutable in C#