Automatic .ToString()?

ε祈祈猫儿з 提交于 2019-11-29 15:27:34

This follows the rules of the C# language specification around string concatenation. See section 7.8.4 of the C# 4 spec (the addition operator)

String concatenation:

string operator +(string x, string y);
string operator +(string x, object y);
string operator +(object x, string y);

These overloads of the binary + operator perform string concatenation. If an operand of string concatenation isnull, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.

If you didn't expect that to happen, may I ask what you expected the result of the "abcdef" + c1 expression to be?

Note that m1, IClass2 and Class2 are irrelevant to what's happening here - it's only the concatenation expression which is really relevant: that's what's triggering the call to ToString(), regardless of what's later happening to that string.

The compiler turns "abcdef" + c1 into a string.Concat(object,object) call. This in turn will call .ToString() on each of the arguments and concatenate them. Here's the code from reflector:

public static string Concat(object arg0, object arg1)
{
   if(arg0 == null) arg0 = Empty;
   if(arg1 == null) arg1 = Empty;

   return (arg0.ToString() + arg1.ToString());
}

Note that the last line involves a call to string.Concat(string, string) where the real concatenation happens.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!