Strings

  • DO use string.IsNullOrEmpty() to check for null or empty conditions.
// Correct
string employeeName = "testing";
if(!string.IsNullOrEmpty(employeeName))
{
}

// Avoid
string employeeName = "testing";
if(employeeName != null && employeeName != "")
{
}

String Concatenation

Strings in C# are immutable which means that a string cannot be changed once it has been created. Any method or operator that appears to be changing the string is actually creating an entirely new string object. This is important to understand before we proceed further.

  • DO use StringBuilder to combine strings in a loop where you don’t know how many source strings you’re combining, and the actual number of source strings may be large.

  • DO use string.Concat or string.Join to concatenate elements of an array or collection of strings.

  • ✅ In other cases, CONSIDER using string interpolation.

    string userName = "<Type your name here>";
    string date = DateTime.Today;
    
    // Use string interpolation to concatenate strings.
    string message = $"Hello {userName}. Today is {date:MMMM dd}.";
    System.Console.WriteLine(message);
    
    message = $"{message} How are you today?";
    System.Console.WriteLine(message);
    

    Why: String interpolation provides a more readable and convenient syntax to create formatted strings than a string composite formatting feature.

Learn more