In C#, a string is an object of the `System.String` class, which represents a sequence of characters. Strings in C# are immutable, meaning once a string is created, it cannot be changed. Every modification to a string results in a new string being created.
string myString = "Hello World!";
In this example, `myString` is a string that holds the text "Hello World!".
Concatenation:
Concatenation is the process of appending one string to the end of another string. The `+` operator can be used for string concatenation.
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // "John Doe"
The `String.Concat()` method can also be used for string concatenation.
string fullName = String.Concat(firstName, " ", lastName); // "John Doe"
Interpolation:
String interpolation provides a more readable and convenient syntax to create formatted strings. The string must be prefixed with a `$` sign to interpret the string as an interpolated string. Inside an interpolated string, you can place an expression within `{}` that will be replaced with its result during string evaluation.
string firstName = "John";
string lastName = "Doe";
string fullName = $"{firstName} {lastName}"; // "John Doe"
Accessing Strings:
Individual characters in a string can be accessed using an indexer with the position (index) of the character in the string. Indexing in C# is zero-based, meaning the first character is at index 0.
string myString = "Hello, World!";
char firstChar = myString[0]; // 'H'
char sixthChar = myString[5]; // ','
String Length:
The length of a string (the number of characters it contains) can be retrieved using the `Length` property.
string myString = "Hello, World!";
int length = myString.Length; // 13
These are just some of the many ways to work with strings in C#. The `System.String` class provides many more methods for string manipulation and querying, such as `Substring`, `Replace`, `Split`, `Trim`, `ToLower`, `ToUpper`, and more.