I know that string.format will insert a specific object, does the same if the string is concatenated?

I read boxing and string.format(). And I found out that he will enter a value type, for example an integer.

So the following code will cause boxing

var number = 5;
var sampleString = string.Format("The number 5: {0}", number);

This code will result in a line

The number 5: 5

However, if I concatenate using the standard operator +, it still produces the same string.

var sampleString = "The number 5: " + number;

What is happening here, is it also transforming the whole into an object?

This also works with a date object, e.g.

var dateString = string.Format("The date: {0}", DateTime.Now);
var dateString = "The date: " + DateTime.Now;

I assume the first line will be a field, but the second line will not be?

+4
source share
1 answer

For: var dateString = "The date: " + DateTime.Now;

+ String.Concat, string.Concat(object,object) . , DateTime.Now .

IL.

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       55 (0x37)
  .maxstack  2
  .locals init ([0] string dateString0,
           [1] string dateString1)
  IL_0000:  ldstr      "The date: {0}"
  IL_0005:  call       valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_Now()
  IL_000a:  box        [mscorlib]System.DateTime
  IL_000f:  call       string [mscorlib]System.String::Format(string,
                                                              object)
  IL_0014:  stloc.0
  IL_0015:  ldstr      "The date: "
  IL_001a:  call       valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_Now()
  IL_001f:  box        [mscorlib]System.DateTime
  IL_0024:  call       string [mscorlib]System.String::Concat(object,
                                                              object)
  IL_0029:  stloc.1
  IL_002a:  ldloc.0
  IL_002b:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0030:  ldloc.1
  IL_0031:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0036:  ret
} // end of method Program::Main

IL,

  IL_0024:  call       string [mscorlib]System.String::Concat(object,
                                                              object)

IL

static void Main(string[] args)
{
    var dateString0 = string.Format("The date: {0}", DateTime.Now);
    var dateString1 = "The date: " + DateTime.Now;
    Console.WriteLine(dateString0);
    Console.WriteLine(dateString1);
}

String.Format .

+4

All Articles