I came across the code similar to the following:
var a = (new string [] {}) + string.Empty;
I would like to ask:
There are 3 + operator overload in .NET Framework.
From C# Spec $7.8.4 Addition operator
string operator + (string x, string y);
string operator + (string x, object y);
string operator + (object x, string y);
That's why your var a = (new string [] {}) + string.Empty; matches the third overload.
And + (object x, string y) uses String.Concat(object, object) overload which is implemented like;
public static String Concat(Object arg0, Object arg1)
{
if (arg0 == null)
{
arg0 = String.Empty;
}
if (arg1==null) {
arg1 = String.Empty;
}
return Concat(arg0.ToString(), arg1.ToString());
}
And since new string [] {} is not null because in MSIL, it uses newarr and it's documentation;
The stack transitional behavior, in sequential order, is:
- The number of elements in the array is pushed onto the stack.
- The number of elements is popped from the stack and the array is created.
- An object reference to the new array is pushed onto the stack.
That's why it uses object.ToString() method at the end.
From it's documentation;
ToString is the major formatting method in the .NET Framework. It converts an object to its string representation so that it is suitable for display.The default implementation of the ToString method returns the fully qualified name of the type
As a result your a will be System.String[].
The C# Language Specification has an overload
string operator +(object x, string y)
which works by calling x.ToString() (if x is not null, otherwise just use "") and concatenate that with y.
Therefore your code should produce the same as
string a = string.Concat((new string[] {}).ToString(), string.Empty);
so now the question is how ToString() is implemented on the string[] type. It turns out that it is not overridden from the implementation from object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With