1

I have text that I need to display to a user, but some of it is based off of a variable which will keep changing, like so:

string s = "The current time is <currentTime>.";

'currentTime' is the variable I need to display. How can I add the value of the variable into the string?

mcargille
  • 135
  • 2
  • 8
  • I don't know how I didn't find that question when I was looking if someone had done this already. You can go ahead and close this. – mcargille Jan 10 '17 at 14:49

1 Answers1

2

If you're using C# 6.0, you can insert variables into a string by creating an Interpolated String. Otherwise your options are concatenation or the String.Format method. Any of these methods will produce the desired result:

The current time is 10:24:43.47344233.

Interpolation

string s = $"The current time is {currentTime}.";

By adding a $ before the first quote, C# will recognize it as an interpolated string, look for variable names inside curly braces, and replace them with their values.

Concatenation

string s = "The current time is " + currentTime + ".";

This basically attaches strings to either side of a variable value. It's pretty straightforward, but it means you need to pay attention to your spacing and formatting.

String.Format

string s = String.Format("The current time is {0}.", currentTime);

This is slightly more complex. The Format method takes a string and any number of expressions as arguments, and inserts the values of the expressions into the string where indicated by the numbered brackets. So {0} will be replaced with the first expression, {1} will be replaced with the second, and so on.

If you want to format the variable values, you can also apply standard numeric or datetime format strings when using either interpolated strings or the String.Format method.

mcargille
  • 135
  • 2
  • 8