Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String array plus string is not error, why?

I came across the code similar to the following:

var a = (new string [] {}) + string.Empty; 

I would like to ask:

  • Why this code can be compiled (why isn`t this error of types) ?
  • How to understand this behavior ?
like image 804
Liashenko V Avatar asked Jan 26 '26 17:01

Liashenko V


2 Answers

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:

  1. The number of elements in the array is pushed onto the stack.
  2. The number of elements is popped from the stack and the array is created.
  3. 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[].

like image 188
Soner Gönül Avatar answered Jan 29 '26 09:01

Soner Gönül


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.

like image 45
Jeppe Stig Nielsen Avatar answered Jan 29 '26 09:01

Jeppe Stig Nielsen