C# String Theory—String operators
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| C# Articles |
| edit |
Contents |
C# String operators
String assignment
Strings can be assigned new values using either of these assignment operators: =, +=.
string testString = "Arthur Schopenhauer"; testString += " (1788-1860)"; Console.WriteLine (testString); // Outputs "Arthur Schopenhauer (1788-1860)"
String index
The [] operator can be used to access individual characters in a string like this (remember the first index into an array is zero):
string string1 = "performant"; char letter = string1[5]; // sixth letter = 'r';
String concatenation
C# strings can be concatenated using the plus (+) operator.
Console.WriteLine ("This statement results " + " in the creation of three strings." );
Also, multiple strings can be concatenated with the String.Concat method.
String overloads the equality operators.
Normally, the == operator calls the Equals method which compares the pointer values found in the reference variables for equality. This tests whether they point to the same object.
However, the String class overloads the the equality operators (==, !=), and changes their behavior. (This is one of the ways in which strings act like value types.) When used to compare two string objects, the == operator checks for equality of the string data values rather than for equality of the references. Be careful, because operator overloading only occurs when both sides of the operator are string expressions at compile time. In the following example, one side is of type Object; so, the overloaded operator is not used; and, the comparison is of pointer values. In this situation, Visual Studio will warn you saying "Possible unintended reference comparison".
string string1 = "value"; Object string2 = "value"; if (string1 == string2) // compares references { Console.WriteLine ("=="); // comparison is true }
|

