Is there a best way to insert variables into strings?
https://softwareengineering.stackexchange.com/questions/403830
题
I am relatively new to programming but have noticed a lot of people when creating strings using variables do something like the below to put a variable into a string. I am curious at the difference/reason why this seems to be preferred by the senior developers I know and to also get opinions on why to use one over the other.
var x = "world";
Console.WriteLine("Hello {0}",x);
Is there an advantage or specific reason as to why the above is used as opposed to this:
var x = "world";
Console.WriteLine("Hello " + x);
Or this
var x = "world";
Console.WriteLine($"Hello {x}");
解决方案
Rather than ask, test it:
using System;
public static class Program
{
public static void Main()
{
X();
Y();
Z();
}
public static void X()
{
var x = "world";
Console.WriteLine("Hello {0}", x);
}
public static void Y()
{
var x = "world";
Console.WriteLine("Hello " + x);
}
public static void Z()
{
var x = "world";
Console.WriteLine($"Hello {x}");
}
}
Look at the IL produced from the different approaches to see what difference it makes.
The "Hello " + x
approach invokes string.Concat
then calls WriteLine
. You could then go off and look at the source of WriteLine
and you'd find it does a string.Concat
anyway.
So in short, there's no real difference and you shouldn't expect there to be: the compiler will tend to sort such things out for you anyway and thus worrying about it is just premature micro-optimising on your part, which is behaviour that should be avoided.
And neither is the ideal way to do it anyway. The third approach in my code above,
var x = "world";
Console.WriteLine($"Hello {x}");
is by far the neatest and clearest way to express it.
其他提示
It's simply that it's easier to read (and write) for longer/more complicated strings or strings where the variable is somewhere in the middle of the string.
Console.WriteLine("Hello, {0}. Happy {1}. The time is {2}.", name, dayOfWeek, time);
vs.
Console.WriteLine("Hello, " + name + ". Happy " + dayOfWeek + ". The time is " + time + ".");
For trivial examples where a variable is just appended to a string it makes very little difference.