String Type


  • System.String
  • Immutable sequence of Unicode characters
  • Specified in double quotes
  • Is reference type
  • Escape sequence valid for char literals work inside strings
    eg string a = "Here's a tab:\t";
  • Whenever backslash is needed you need to write twice
    string a1 = "\\\\server\\fileshare\\helloworld.cs";

Verbatim String Literals

  • C# allows verbatim string literals, prefixed with @ and does not support escape sequence
    eg: string a2 = @ "\\server\fileshare\helloworld.cs";
  • Include double-quote character in a verbatim literal by writing twice
    string xml = @"";

String concatenation

  • + operator concatenates two strings
    string s = "a" + "b";
  • If one of the value is non string, ToString() method is called on the value
    string s = "a" + 5; // a5

Better solution to use:

String interpolation (C# 6)

String preceded with the $ character is called an interpolated string

Interpolated strings can include expressions inside braces

int x = 4;
Console.Write ($"A square has {x} sides"); // Prints: A square has 4 sides

To change the format

string s = $"255 in hex is {byte.MaxValue:X2}"; // X2 = 2-digit Hexadecimal
// Evaluates to "255 in hex is FF"

int x = 2;
string s = $@"this spans {
x} lines";

String comparisons

Use CompareTo() method

Leave a Reply

Your email address will not be published. Required fields are marked *