In this article, we are going to explore how to use variables inside strings in C#. There are a few ways to accomplish that, depending on the C# version being used.

To download the source code for this article, you can visit our GitHub repository.

So, let’s start

Concatenating Variables in C#

The common way of inserting variables into strings is to use the + operator:

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!
var myNumber = 5;
var myText = "My number is " + myNumber + " but I can count way more";

The + operator allows us to concatenate strings, that is, to join strings together.

For primitive data types, this works pretty well. But in case we use classes or structs, we want to override their ToString() method:

public class MyClass
{
    public var MyNumber { get; set; }

    public MyClass(int num)
    {
        MyNumber = num;
    }

    public override string ToString()
    {
        return MyNumber.ToString();
    }
}

Now, we can use this class to get the output we want:

var number = new MyClass(3); 
var numberText1 = "My number is " + number; 
var numberText2 = "My number is " + number.ToString();

It’s not necessary to call ToString() directly as it’s being done internally.

Using string.Format()

Another way to include variables in a string is to use the string.Format() method:

var apples = 10;
var bananas = 6;
string.Format("I have {0} apples, {1} bananas and {2} pears", apples, bananas, 3);

We replace the {x} placeholders with the other arguments in the function in the order they come in, with {0} being the first argument, {1} the second argument, and so on.

Moreover, this allows to re-use the same arguments or to mix them in different positions:

var apples = 10;
var pears = 6;
string.Format("I have {0} apples, {2} bananas and {1} pears. Did I mention I have {2} bananas?", apples, pears, 3);

Using String Interpolation

Starting with version 6, C# allows string interpolation, which conveys a more “natural” flow to the syntax:

var myApples = 2;
var myPears = 5;
var myBananas = 10;
string myString = $"I have {myApples} apples, {myPears} pears and {(myApples > 2 ? myBananas : myBananas + 5)} bananas";

Prefixing a string literal with $ allows us to interpret any content inside a pair of curly brackets as language expressions. They get evaluated and the result is converted to a string automatically.

If we want to use curly brackets in our text, we need to escape them with another matching bracket:

var word = "too";
$"{{I am just a regular string}}! This other string is {word}.";

Conclusion

In this article, we have covered three ways to mix variables inside strings in C#. String interpolation is the most recent method and likely the easiest one to write and understand.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!