Export (0) Print
Expand All

string (C# Reference)

The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:


      string a = "hello";
string b = "h";
// Append to contents of 'b'
b += "ello";
Console.WriteLine(a == b);
Console.WriteLine((object)a == (object)b);

This displays "True" and then "False" because the content of the strings are equivalent, but a and b do not refer to the same string instance.

The + operator concatenates strings:


      string a = "good " + "morning";

This creates a string object that contains "good morning".

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and the variable b continues to hold "h".


      string b = "h";
b += "ello";

The [] operator can be used to access individual characters of a string:


      string str = "test";
char x = str[2];  // x = 's';

String literals are of type string and can be written in two forms, quoted and @-quoted. Quoted string literals are enclosed in double quotation marks ("):

"good morning"  // a string literal

String literals can contain any character literal, including escape sequences:


      string a = "\\\u0066\n";

This string contains a backslash, the letter f, and new line.

NoteNote

The escape code \udddd (where dddd is a four-digit number) represents the Unicode character U+dddd. Eight-digit Unicode escape codes are also recognized: \udddd\udddd.

@-quoted string literals start with @ and are also enclosed in double quotation marks. For example:

@"good morning"  // a string literal

The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:

@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"

To include a double quotation mark in an @-quoted string, double it:

@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.

Another use of the @ symbol is to use referenced (/reference) identifiers that happen to be C# keywords.

// keyword_string.cs
using System;
class TestClass 
{
   static void Main()
   {
      string a = "\u0068ello ";
      string b = "world";
      Console.WriteLine( a + b );
      Console.WriteLine( a + b == "hello world" );
   }
}

Output

 
hello world
True

For more information, see the following sections in the C# Language Specification:

  • 2.4.2 Identifiers

  • 2.4.4.5 String literals

  • 4.2.3 The string type

  • 7.9.7 String equality operators

Community Additions

ADD
Show:
© 2015 Microsoft