C# has a lot of data types and some aren’t even used. We often use them without really knowing why we use them and what the data types are capable of. In the series “The C# data types”, I show you a few of those data types and look into them. Some basic examples, tips, and tricks. In this article: string.
The String
A string is the most commonly used data type in C# and other languages. It’s used to contain text and text is all the characters you can imagine.
Basic usage
A string is usually initialized with the text surrounded by quotes. It’s also possible to initialize it with NULL.
string message = "Hello world"; // Initialize string with text
string message2 = null; // Initialize string with null
string message3 = "You can also put numbers in a string: 12345. Or other chars #$(!&";
string number1 = "1";
string number2 = "2";
string totalNumber = number1 + number2; // This is not 3, but it's 12
String vs System.String
There are two string keywords. One is the string (lower s) and String (capital s). The second is the class, used for accessing certain static methods. You can use the String for declaring variables and adding values to them, but you will need to add a using to System. With the string (lower s) you don’t need to add any usings.
But in the end, there isn’t much difference between both strings. The string is an alias for System.String, so it has all the functionalities of the System.String. The latter is used for static methods like Format, IsNullOrEmpty, IsNullOrWhitespace, ToLower, ToUpper, and more.
Common string actions
Concatenate
A way to combine two or more strings into one string. There are several tricks of doing this.
string first = "This is the first.";
string second = "This is the second.";
string total = first + second; // Using the + operator
string total2 = $"{first}{second}"; // String interpolation
first += second; // Using the += operator
string total3 = String.Format("{0}{1}", first, second); // Using the String.Format()
While the above examples are all correct and working, string interpolation and the += operator are proven to have the best performance. It really depends on what you try to achieve in your code.
ToLower and ToUpper
Two methods that are very valuable when doing checks. If you want to check if value 1 has the same content as value 2 it’s best to convert all characters to lower cases or upper cases.
string first = "AbcdEfg";
string second = "abcdefg";
if(first == second) // This is false
Console.WriteLine("Yes! They are the same");
if(first.ToLower() == second.ToLower()) // This is true
Console.WriteLine("Yes! They are the same");
Length
A read-only property that returns the number of characters of the string. You can’t set the length.
string text = "Hello world";
Console.WriteLine(text.Length); // Will show 11
StringBuilder
A StringBuilder is used to easily hold and concatenate strings. It works a bit like a list, but it has different methods. You can add text or lines to the StringBuilder. When you are done you can convert the StringBuilder to a string.
using System.Text;
StringBuilder sb = new();
sb.Append("Add text to the StringBuilder");
sb.AppendLine("This text will be placed directly after the previous append, but the next append(line) will be on a new line.");
sb.AppendLine("Append line will add a new line to the string builder.");
string totalText = sb.ToString();
Console.WriteLine(totalText);
The result:

ToString
Maybe the most used function for a string. ToString converts almost everything to a string. For example an integer:
int year = 2021;
string stringYear = year.ToString();
If you try to add 1 to the stringYear you will get “20211”, not 2022, which is the case if you add 1 on the year variable.
If you use ToString on classes that don’t have the ToString implemented or overridden it will return the full name of the class, including the namespace.
using Some.Other.NameSpace;
Movie movie = new()
{
Title = "The Matrix",
Rating = 5
};
Console.WriteLine(movie.ToString()); // This will show Some.Other.Namespace.Movie
namespace Some.Other.NameSpace
{
public class Movie
{
public string Title { get; set; }
public int Rating { get; set; }
public void SetRating(int rating)
{
Rating = rating;
}
}
}
But if we would override the ToString on the Movie class it could look like this:
using Some.Other.NameSpace;
Movie movie = new()
{
Title = "The Matrix",
Rating = 5
};
Console.WriteLine(movie.ToString());
namespace Some.Other.NameSpace
{
public class Movie
{
public string Title { get; set; }
public int Rating { get; set; }
public void SetRating(int rating)
{
Rating = rating;
}
public override string ToString()
{
return $"{Title} has a rating of {Rating}";
}
}
}
PadLeft and PadRight
These two will add whitespaces in front (PadLeft) or behind (PadRight) of the string. A good way to align text in a console application for example.
string text = "Hello world";
string secondText = "Bye!";
Console.WriteLine(text);
Console.WriteLine(secondText.PadLeft(11));
Replace
Replace is a wonderful method to replace a certain part of the contents of the string. The method Replace will create a new string and replaces all occurrences with the new value.
string thisShouldBeMadeUrlFriend = "Hello world! #DefaultText";
string urlText = thisShouldBeMadeUrlFriend
.Replace("!", string.Empty)
.Replace("#", string.Empty)
.Replace("_", string.Empty)
.Replace("Hello", "Goodbye")
.ToLower();
// Will result in goodbye_world_defaulttext
SubString
The SubString lets you grab a specific part of the content of the string. It works with positions (int).
string exampleText = "Hello world! #DefaultText";
// Only get the first 5 characters from the beginning
string substring1 = exampleText.Substring(5); // Will return " world! #DefaultText"
// Start a position, get until position 5
string substring2 = exampleText.Substring(6, 5); // Will return "world"
// Get the word "DefaulText" only.
// Not the most elegant way, but showing you the possibilities.
string substring3 = exampleText.Substring(exampleText.Length - "#DefaultText".Length + 1, "DefaultText".Length); // Will return "DefaultText"
Split
This literally splits the string into pieces, placing the pieces in an array. Ideally to real URL segments or other strings where you need that one, little piece of text.
The Split() gets one parameter, which is the char on which the string should be split.
string exampleText = "https://kenslearningcurve.com/tutorials/the-minimal-api-with-net-6/";
string[] elements = exampleText.Split("/");
string category = elements[3]; // This will be 'tutorials'
Trim
The Trim-method will remove empty spaces at the front and back of a string. Perfect for cleaning up user input.
string exampleText = " UserEmail@someemail.com "; // This has spaces in the front and back of the e-mail.
Console.WriteLine(exampleText.Trim()); // Will show the same e-mail, but without the spaces.
Trim removes spaces on both sides, not in between. If you want to remove spaces at the front, use TrimStart(). TrimEnd() will remove spaces at the end of the string.
If you want to remove spaces in the middle of a string, use Replace().
Validations
It’s pretty common to check the contents of a string. Whether it has a certain value or if it’s empty, most validations are easy to do.
String.IsNullOrEmpy
Checks if the string, parameter, is null or empty.
string text = "";
if (string.IsNullOrEmpty(text))
Console.WriteLine("Correct");
else
Console.WriteLine("String is not null or empty.");
text = string.Empty;
if (string.IsNullOrEmpty(text))
Console.WriteLine("Correct");
else
Console.WriteLine("String is not null or empty.");
text = null;
if (string.IsNullOrEmpty(text))
Console.WriteLine("Correct");
else
Console.WriteLine("String is not null or empty.");
text = "Hello world";
if (string.IsNullOrEmpty(text))
Console.WriteLine("Correct");
else
Console.WriteLine("String is not null or empty.");
Contains
A function that returns true if a string contains a specific set of one or more characters.
string text = "Hello world";
if (text.Contains("or"))
Console.WriteLine("Yes, it contains 'or'");
To avoid problems with uppercase and lowercase characters it is wise to use the StringComparison option. This will allow you to choose whether you want to ignore uppercase characters or not.
string text = "Hello wOrld"; // Note the capital O!
if (text.Contains("or")) // Is false
Console.WriteLine("Yes, it contains 'or'");
else
Console.WriteLine("There is no 'or' in the text.");
if (text.Contains("or", StringComparison.CurrentCultureIgnoreCase)) // Is true
Console.WriteLine("Yes, it contains 'or'");
else
Console.WriteLine("There is no 'or' in the text.");
StartsWith and EndsWith
These two determine if a string starts or ends with a specific value. This way you can check whether you want to handle a specific string or not.
string exampleText = "https://kenslearningcurve.com/about-me/";
if (exampleText.StartsWith("https"))
Console.WriteLine("This URL starts with HTTPS and is safe.");
if (exampleText.EndsWith("/aboutme"))
Console.WriteLine("This is my personal page. Always show it, whether it is HTTP or not.");
Conslusion for string
The string is a powerful data type that we all use. It’s especially easy when using and handling text since the string can hold all the characters we have.
Putting all the methods and functions of the string on this page is impossible and written down many times by others. This article contains the methods and functions most used. If you want to have a full view of this data type, check out the Microsoft documentation for more.
If you think some method or trick is missing, let me know!