[.net] String Optimizations in C#

Started by
3 comments, last by Brice Lambson 15 years, 10 months ago
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..
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?
Advertisement
Damnit.

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.
if you want an unique identifier, use Guid.NewGuid().

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

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.
--Brice Lambson

This topic is closed to new replies.

Advertisement