Sobes.tech
Intern

What is a string in C#?

sobes.tech AI

Answer from AI

A string in C# is an immutable sequence of Unicode characters.

Main characteristics:

  1. Immutability: Once a string object is created, its contents cannot be changed. Any operation that appears to modify a string (for example, concatenation) actually creates a new string object.
  2. Type: string is a reference type (System.String), but behaves largely like a value type due to overloaded operators and special compiler handling.
  3. Literals: String literals are enclosed in double quotes ("...").
  4. @-literals: For strings with escape characters or multiline strings, it is convenient to use verbatim string literals (with the @ symbol before the quote).
  5. String interpolation: Syntax $"{...}" for embedding variable values and expressions into a string.

Examples:

string name = "Ivan"; // String literal
string greeting = $"Hello, {name}!"; // String interpolation
string path = @"C:\Program Files\MyApp\"; // Verbatim literal

Immutability is important for security and performance in certain scenarios (for example, when using strings as keys in dictionaries). For creating mutable strings, classes like StringBuilder are used.

using System.Text;

StringBuilder sb = new StringBuilder();
sb.Append("First part.");
sb.Append(" Second part.");
string finalString = sb.ToString(); // "First part. Second part."