Purpose String.Concat (Object) instead of String.Concat (String)

What is the purpose of using String.Concat(Object) instead of String.Concat(String) in C #? Why not just use an implicit call to Object.ToString() instead of passing the object itself, which can also cause boxing?

 Int32 i = 5; String s = "i = "; // Boxing happens, ToString() is called inside Console.WriteLine(s + i); // Why compiler doesn't call ToString() implicitly? Console.WriteLine(s + i.ToString()); 

Gives us the next IL.

 .method private hidebysig static void MyDemo() cil managed { // Code size 47 (0x2f) .maxstack 2 .locals init ([0] int32 i, [1] string s) IL_0000: nop IL_0001: ldc.i4.5 IL_0002: stloc.0 IL_0003: ldstr "i = " IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: box [mscorlib]System.Int32 IL_0010: call string [mscorlib]System.String::Concat(object, object) IL_0015: call void [mscorlib]System.Console::WriteLine(string) IL_001a: nop IL_001b: ldloc.1 IL_001c: ldloca.si IL_001e: call instance string [mscorlib]System.Int32::ToString() IL_0023: call string [mscorlib]System.String::Concat(string, string) IL_0028: call void [mscorlib]System.Console::WriteLine(string) IL_002d: nop IL_002e: ret } // end of method Program::MyDemo 
+8
string c # clr boxing
source share
2 answers

Why would the compiler do this? He can not.

If you pass an object (in this case, in an int box), the only option for the compiler is to call string.Concat(object, object) . It cannot call string.Concat(string, string) , since both parameters are not string and therefore correspond to the second overload.

Instead, it calls string.Concat(object, object) and makes a ToString inside, if applicable.

You, as a developer, know how the string.Concat method string.Concat . The compiler does not know that eventually everything will become string .

Also, what happens if one of the object is null ? ToString will fail. It does not make sense. Just go to object and let the code handle it.

+3
source share

Link source: http://referencesource.microsoft.com/#mscorlib/system/string.cs,8281103e6f23cb5c

Shows that:

  public static String Concat(Object arg0) { Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); if (arg0 == null) { return String.Empty; } return arg0.ToString(); } 

It just creates a string representation of this object. That way, any object you pass is converted to String . String.Empty if it is zero. I think this also prevents us from checking the "null" object before converting it to String .

0
source share

All Articles