Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C# string interpolation without an expression compile?

How does the compiler handle interpolated strings without an expressions?

string output = $"Hello World";

Will it still try to format the string? How does the compiled code differ from that of one with an expression?

like image 513
roydukkey Avatar asked May 14 '16 22:05

roydukkey


People also ask

What does %d do in C?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

How does C operate?

c is called the source file which keeps the code of the program. Now, when we compile the file, the C compiler looks for errors. If the C compiler reports no error, then it stores the file as a . obj file of the same name, called the object file.

What is && operator in C?

The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 . The type of the result is int . Both operands must have an arithmetic or pointer type.

What is -= in C?

-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A.


1 Answers

For this C# code:

string output = $"Hello World";

int integer = 5;

string output2 = $"Hello World {integer}";

Console.WriteLine(output);

Console.WriteLine(output2);

I get this when I compile and then decompile (via ILSpy):

string value = "Hello World";
int num = 5;
string value2 = string.Format("Hello World {0}", num);
Console.WriteLine(value);
Console.WriteLine(value2);

So it seems that the compiler is smart enough not to use string.Format for the first case.

For completeness, here is the IL code:

IL_0000: nop
IL_0001: ldstr "Hello World"
IL_0006: stloc.0
IL_0007: ldc.i4.5
IL_0008: stloc.1
IL_0009: ldstr "Hello World {0}"
IL_000e: ldloc.1
IL_000f: box [mscorlib]System.Int32
IL_0014: call string [mscorlib]System.String::Format(string, object)
IL_0019: stloc.2
IL_001a: ldloc.0
IL_001b: call void [mscorlib]System.Console::WriteLine(string)
IL_0020: nop
IL_0021: ldloc.2
IL_0022: call void [mscorlib]System.Console::WriteLine(string)
IL_0027: nop
IL_0028: ret

It is clear here too that string.Format is only called for the second case.

like image 83
Yacoub Massad Avatar answered Sep 22 '22 22:09

Yacoub Massad