C# String Type

Description

C#'s string type represents an immutable sequence of Unicode characters.

Aliasing the System.String type.

string literal

A string literal is specified inside double quotes:

string a = "java2s.com";

Equality

string is a reference type, rather than a value type. Its equality operators, however, follow value-type semantics:


string a = "test"; 
string b = "test"; 
Console.Write (a == b);  // True 

Escape Sequences

The escape sequences that are valid for char literals also work inside strings:


     string a = "Here's a tab:\t";
     

Verbatim string literals

C# allows verbatim string literals.

A verbatim string literal is prefixed with @ and does not support escape sequences.

The following example shows how to create verbatim string:

 
string a2 = @ "\\server\fileshare\helloworld.cs";

A verbatim string literal can also span multiple lines:


string escaped  = "First Line\r\nSecond Line"; 
string verbatim = @"First Line 
Second Line"; 

You can include the double-quote character in a verbatim literal by writing it twice:


string xml = @"<customer id=""123""></customer>"; 

String concatenation

The + operator concatenates two strings:


string s = "a" + "b"; 

The right hand operand may be a nonstring value, in which case ToString is called on that value. For example:


string s = "a" + 5;  // a5 

Null and empty strings

An empty string has a length of zero.

To create an empty string, you can use either a literal or the static string.Empty field; to test for an empty string, you can either perform an equality comparison or test its Length property:


string empty = "";
Console.WriteLine (empty == "");              // True
Console.WriteLine (empty == string.Empty);    // True
Console.WriteLine (empty.Length == 0);        // True
//  w  ww. ja v  a  2  s  .c  o m

Because strings are reference types, they can also be null:


string nullString = null;//  w w  w.jav  a2 s  . co  m
Console.WriteLine (nullString == null);        // True
Console.WriteLine (nullString == "");          // False
Console.WriteLine (nullString.Length == 0);    // NullReferenceException

The static string.IsNullOrEmpty method is a useful shortcut for testing whether a given string is either null or empty.

String indexer

A string's indexer returns a single character at the given index. As with all functions that operate on strings, this is zero-indexed:


string str  = "abcde";
char letter = str[1];        // letter == 'b'

string also implements IEnumerable<char>, so you can foreach over its characters:


foreach (char c in "123") 
   Console.Write (c + ",");    // 1,2,3,





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var