If I have a format string that utilizes the same place holder multiple times, like:
emailBody = $"Good morning {person.GetFullName()}, blah blah blah, {person.GetFullName()} would you like to play a game?";
does person.GetFullName()
get evaluated twice, or is the compiler smart enough to know these are the same value, and should be evaluated once?
Yes, it will be evaluated twice. It can't know that it is the same value. For example:
Random rng = new Random();
Console.WriteLine($"{rng.Next(5)}, {rng.Next(5)}, {rng.Next(5)}");
It's exactly the same as if you just used the expression as a method argument - if you called:
Console.WriteLine("{0} {1}", person.GetFullName(), person.GetFullName());
... you'd expect GetFullName
to be called twice then, wouldn't you?
If you only want to evaluate it once, do so beforehand:
var name = person.GetFullName();
emailBody = $"Good morning {name}, blah blah blah, {name} would you like to play a game?";
Or just use a normal string.Format
call:
emailBody = string.Format(
"Good morning {0}, blah blah blah, {0} would you like to play a game?",
person.GetFullName());
See more on this question at Stackoverflow