X hits on this document

1020 views

0 shares

0 downloads

0 comments

165 / 396

C# LANGUAGE SPECIFICATION

class Test { static void Main() { string s = "Test"; string t = string.Copy(s); Console.WriteLine(s == t); Console.WriteLine((object)s == t); Console.WriteLine(s == (object)t); Console.WriteLine((object)s == (object)t); } }

produces the output

True False False False

The s and t variables refer to two distinct string instances containing the same characters. The first comparison outputs True because the predefined string equality operator (§‎7.9.7) is selected when both operands are of type string. The remaining comparisons all output False because the predefined reference type equality operator is selected when one or both of the operands are of type object.

Note that the above technique is not meaningful for value types. The example

class Test { static void Main() { int i = 123; int j = 123; System.Console.WriteLine((object)i == (object)j); } }

outputs False because the casts create references to two separate instances of boxed int values.

7.9.7 String equality operators

The predefined string equality operators are:

bool operator ==(string x, string y);

bool operator !=(string x, string y);

Two string values are considered equal when one of the following is true:

Both values are null.

Both values are non-null references to string instances that have identical lengths and identical characters in each character position.

The string equality operators compare string values rather than string references. When two separate string instances contain the exact same sequence of characters, the values of the strings are equal, but the references are different. As described in §‎7.9.6, the reference type equality operators can be used to compare string references instead of string values.

7.9.8 Delegate equality operators

Every delegate type implicitly provides the following predefined comparison operators:

bool operator ==(System.Delegate x, System.Delegate y);

152Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views1020
Page views1020
Page last viewedFri Dec 09 22:30:32 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments