Strings in C#

In C#, strings are used to represent text data. Strings are immutable, which means that once a string is created, it cannot be modified. Instead, any string operation that appears to modify the string actually creates a new string.

Here are some of the key concepts related to strings in C#:

1. String declaration: To declare a string in C#, you use the “string” keyword followed by the name of the string variable. For example:

string message = "Hello, world!";

This code creates a string variable named “message” and assigns it the value “Hello, world!”.

2. Accessing string characters: You can access individual characters of a string using the index of the character, which starts at 0. For example:

char firstChar = message[0]; // returns 'H'
char secondChar = message[1]; // returns 'e'

This code accesses the first and second characters of the “message” string.

3. String concatenation: You can concatenate two or more strings in C# using the “+” operator. For example:

string firstName = "Alice";
string lastName = "Smith";
string fullName = firstName + " " + lastName; // returns "Alice Smith"

This code concatenates the “firstName” and “lastName” strings with a space in between to create the “fullName” string.

4. String interpolation: String interpolation is a feature in C# 6 and later versionsthat allows you to embed expressions directly into string literals. To use string interpolation, you enclose the expression in curly braces inside the string literal. For example:

string firstName = "Alice";
string lastName = "Smith";
string fullName = $"{firstName} {lastName}"; // returns "Alice Smith"

This code uses string interpolation to create the “fullName” string by embedding the “firstName” and “lastName” variables directly inside the string literal.

5. String methods: Strings provide a variety of methods for manipulating and working with strings. For example:

string message = "Hello, world!";
int length = message.Length; // returns 13
string upperCase = message.ToUpper(); // returns "HELLO, WORLD!"
string lowerCase = message.ToLower(); // returns "hello, world!"
bool startsWithHello = message.StartsWith("Hello"); // returns true
bool containsWorld = message.Contains("world"); // returns true

This code uses various string methods to get the length of the “message” string, convert it to upper and lower case, and check whether it starts with “Hello” or contains “world”.

Strings are a fundamental type in C# and are used extensively in most C# programs. By using strings, you can work with text data and perform a wide variety of string operations.