Working with Strings in C#

Strings are a fundamental data type in C# used to work with text data. This comprehensive guide will walk you through the basics of working with strings in C#, including string creation, manipulation, and common string operations.

Creating Strings

In C#, you can create strings using double-quoted or verbatim string literals. Here's how you can create strings:

string message = "Hello, C#";
string path = @"C:\Program Files\CSharp\";

String Concatenation

You can concatenate strings using the + operator or the String.Concat method:

string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // Using the + operator
string result = string.Concat("The answer is: ", 42); // Using String.Concat

String Interpolation

String interpolation allows you to embed expressions within strings using the $ symbol:

string name = "Alice";
int age = 30;
string message = $"Hello, my name is {name} and I am {age} years old.";

String Methods

C# provides a variety of built-in methods for working with strings, such as Length, ToUpper, ToLower, Substring, and more:

string text = "This is a sample string.";
int length = text.Length;
string upper = text.ToUpper();
string lower = text.ToLower();
string sub = text.Substring(5, 7); // Extract "is a sa"

String Comparison

You can compare strings using methods like Equals and Compare:

string str1 = "apple";
string str2 = "banana";
bool areEqual = string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase); // Case-insensitive comparison
int result = string.Compare(str1, str2); // Result is less than 0


Working with strings is a fundamental skill in C# programming. You've learned how to create strings, concatenate them, use string interpolation, and perform common string operations.

Practice manipulating strings in your C# programs to handle text data effectively and explore more advanced topics like regular expressions and string formatting as you advance in your programming journey.