Using variables in strings in C#

Strings are great. Letters, numbers and symbols, all at the same time?

Awesome

Soon enough hard coded strings aren’t going to cut it and you’ll want them to be more dynamic.

Below are 3 methods of mixing variables with your strings:

The Concat Operator +

The + operator when used on string variables will allow you to join them together.

So given the variables firstName and lastName, we could join them together like so:

string firstName = "Frank";
string lastName = "Castle";
string fullName = firstName + lastName;
Console.WriteLine(fullName);

If you run this example your output will be “FrankCastle”.

Unfortunately this doesn’t give us exactly what we want.

To add a space to separate the names, update your code to the following:

string firstName = "Frank";
string lastName = "Castle";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName);

This will output “Frank Castle”. Exactly what we want.

As you can see, we’ve added an extra string in between the 2 variables with no characters, just a single space.

For those unfamiliar, Frank Castle has an alias, let’s add that in between his firstName and lastName for full effect.

string firstName = "Frank";
string lastName = "Castle";
string fullName = firstName + " 'The Punisher' " + lastName;
Console.WriteLine(fullName);

The output will be: “Frank ‘The Punisher’ Castle”.

Something to note is we’ve used (single quotes) rather than (double quotes) purposefully, so we don’t need to worry about “escaping” the double quotes. I’ll cover that in a future post.

Just to reiterate, we could have used the following to get our fullName variable, but we lose the flexibility and context that our variable names provide:

string fullName = "Frank" + " 'The Punisher' " + "Castle";

String.Format()

.Net comes with lots of handy functionality built in. The String.Format() function helps simplify string concatenation by allowing us to define how we want the output string to be structured, and then pass in the variables to use as argument after.

In order to achieve the output from our previous example we can use the following code:

string firstName = "Frank";
string lastName = "Castle";
string fullName = String.Format("{0} {1}", firstName, lastName);
Console.WriteLine(fullName);

The output again will be: “Frank Castle”.

To explain what is happening, the Format function is taking 3 arguments, the first is a string, the second and third are our variables. In the format string we are defining where we want our variables to be in the output string. {0} is our firstName argument, and {1} is our lastName argument. The reason we access them as 0 and 1 and not as 1 and 2 as you might expect is because in C# we use zero-based numbering. You will come across this when you use loops, arrays and lists. What it means to us is that our first item is located at position 0 and our second is at position 1.

Something nice is that we can now easily move our variables. If we wanted the output to read “Castle Frank”, we can do the following:

string firstName = "Frank";
string lastName = "Castle";
string fullName = String.Format("{1} {0}", firstName, lastName);
Console.WriteLine(fullName);

By swapping the index values our output string displays as expected.

We can also duplicate values by repeating their index. To get the output string “Frank Frank Castle” we do the following:

string firstName = "Frank";
string lastName = "Castle";
string fullName = String.Format("{0} {0} {1}", firstName, lastName);
Console.WriteLine(fullName);

Something else to be aware of is we can add in extra text as we please. To give Frank his full title, we just need:

string firstName = "Frank";
string lastName = "Castle";
string fullName = String.Format("{0} 'The Punisher' {1}", firstName, lastName);
Console.WriteLine(fullName);

We are still using single quotes so we don’t have to do any “escaping”.

String Interpolation

Saving the best ’til last, string interpolation. We get the simplicity offered by String.Format() and the clarity from the concatenation operator.

By simply adding a $ in front of our first double quote, we can use our variables by name. Our 3 example from above are reflected below:

string firstName = "Frank";
string lastName = "Castle";
string fullName = "{firstName} {lastName}";
Console.WriteLine(fullName);

Outputs: “Frank Castle”

string firstName = "Frank";
string lastName = "Castle";
string fullName = $"{firstName} {firstName} {lastName}";
Console.WriteLine(fullName);

Outputs: “Frank Frank Castle”

string firstName = "Frank";
string lastName = "Castle";
string fullName = $"{firstName} 'The Punisher' {lastName}";
Console.WriteLine(fullName);

Outputs: “Frank ‘The Punisher’ Castle”

Conclusion

By now this code should make sense and you should understand each method and be able to find one which suits your situation.

In practice I only use string interpolation now, but it is good to know what options are available, and forget the ones you don’t need.

An honourable mention is the StringBuilder class, which offers increased performance when dealing with lots of concatenations, and is probably worth another post in itself.

That wraps up the first post in my series for beginners, hopefully it has been useful.

More Reading

If you’d like some more information on how the + operator works see this StackOverflow answer for more details.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s