Strings and Equality
As fully explained in Chapter 4, a reference type is an object allocated on the garbage-collected managed
heap. By default, when you perform a test for equality on reference types (via the C# == and !=
operators), you will be returned true if the references are pointing to the same object in memory.
However, even though the string data type is indeed a reference type, the equality operators have been
redefined to compare the values of string objects, not the object in memory to which they refer.
static void StringEquality()
{
Console.WriteLine("=> String equality:");
string s1 = "Hello!";
string s2 = "Yo!";
Console.WriteLine("s1 = {0}", s1);
Console.WriteLine("s2 = {0}", s2);
Console.WriteLine();
// Test these strings for equality.
Console.WriteLine("s1 == s2: {0}", s1 == s2);
Console.WriteLine("s1 == Hello!: {0}", s1 == "Hello!");
Console.WriteLine("s1 == HELLO!: {0}", s1 == "HELLO!");
Console.WriteLine("s1 == hello!: {0}", s1 == "hello!");
Console.WriteLine("s1.Equals(s2): {0}", s1.Equals(s2));
Console.WriteLine("Yo.Equals(s2): {0}", "Yo!".Equals(s2));
Console.WriteLine();
}
The C# equality operators perform a case-sensitive, character-by-character equality test on string
objects. Therefore, "Hello!" is not equal to "HELLO!", which is different from "hello!". Also, keeping the
connection between string and System.String in mind, notice that we are able to test for equality using
the Equals() method of String as well as the baked-in equality operators. Finally, given that every string
literal (such as "Yo") is a valid System.String instance, we are able to access string-centric functionality
from a fixed sequence of characters.
No comments:
Post a Comment