Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does string interpolation evaluate duplicated usage?

Tags:

c#

c#-6.0

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?

like image 216
Nathan Tregillus Avatar asked Jun 17 '15 16:06

Nathan Tregillus


People also ask

What is the purpose of string interpolation?

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.

Which character should be used for string interpolation?

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.

What is string interpolation in TypeScript?

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.

Why do we use string interpolation in C#?

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.


1 Answers

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()); 
like image 114
Jon Skeet Avatar answered Oct 03 '22 21:10

Jon Skeet