String x = "abc";
String y = "abc";
...and both x and y may get optimized to have the same memory location. Thus, the reference cannot be used as a unique identifier.
Does C# do this also?
[.net] String Optimizations in C#
I'm working on a List control, and I'm wondering if I can use the string reference as a unique identifier for its position in the list.
In Java, you can write..
Damnit.
Looks like I'll have to write something like..
class cSafeString
{
public string MyString;
}
Quote:Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (Section 7.9.7) appear in the same assembly, these string literals refer to the same string instance. For instance, the output produced by
Copy Code
class Test
{
static void Main() {
object a = "hello";
object b = "hello";
System.Console.WriteLine(a == b);
}
}
is True because the two literals refer to the same string instance.
- http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx
Looks like I'll have to write something like..
class cSafeString
{
public string MyString;
}
in C# you can use the == to test two string for equality because it has operator overloading so in C# "a == b" is the same as "a.equals(b)" in java.
Quote:
Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references (7.9.7 String equality operators). This makes testing for string equality more intuitive.
Object.ReferenceEquals()
will test to see if the references (not the values) of the two strings are equal, but be warned, the compiler optimizes identical literals to be the same instance.string a = "test";string b = "test";Object.ReferenceEquals(a, b); // returns true due to compiler.a = Console.ReadLine(); // If it type in "test"b = Console.ReadLine(); // and "test" again...Object.ReferenceEquals(a, b); // returns false this time.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement