C# Strings Introduction

In C#, a string is a sequence of characters enclosed in double quotes (""). Strings are immutable, meaning their values cannot be changed once they are created. C# provides several methods for working with strings, such as concatenation, interpolation, and accessing specific characters.

Strings are one of the most commonly used data types in C#, and the string class is defined in the System namespace.

Key Topics

1. String Declaration

You can declare and initialize strings in C# as follows:

Example: Declaring Strings

string greeting = "Hello, World!";
string emptyString = "";  // An empty string
string nullString = null;  // A null string

2. String Immutability

Strings in C# are immutable. When you modify a string, a new string object is created in memory.

Example: String Immutability

string original = "Hello";
string modified = original + " World";
Console.WriteLine(original);   // Outputs: Hello
Console.WriteLine(modified);   // Outputs: Hello World

3. Common String Methods

C# provides various methods for string manipulation, such as Length, ToUpper(), and Contains().

Example: Using String Methods

string sample = "Hello World";
Console.WriteLine(sample.Length);         // Outputs: 11
Console.WriteLine(sample.ToUpper());      // Outputs: HELLO WORLD
Console.WriteLine(sample.Contains("World")); // Outputs: True

Key Takeaways

  • Strings are sequences of characters enclosed in double quotes.
  • They are immutable; modifications create new string objects.
  • The string class offers many methods for manipulation.