Compartir a través de


string (C# Reference) 

The string type represents a string of Unicode characters. string is an alias for String in the .NET Framework. Strings are immutable--the contents of a string object cannot be changed after the object is created.

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".

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.

Note

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. For more information, see 2.4.2 Identifiers.

Example

// 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

C# Language Specification

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

  • 2.4.4.5 String literals

  • 4.2.3 The string type

  • 7.9.7 String equality operators

See Also

Reference

C# Keywords
Reference Types (C# Reference)
Value Types (C# Reference)

Concepts

C# Programming Guide
C# Programming Guide

Other Resources

C# Reference
Formatting Numeric Results Table (C# Reference)