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?
In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.
To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal.
TypeScript String Interpolation is an expression used to evaluate string literals that contain one or more expressions. String Interpolation evaluates the expressions and obtains the result in a string, which is then replaced in the original string.
C# string interpolation is used to format and manipulate strings. This feature was introduced in C# 6. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation. C# string interpolation is a method of concatenating, formatting and manipulating strings.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With