Search code examples
c#dynamicnullconcatenation

Why is concatenation called when using dynamic obj + class obj?


I have such an example code:

static void Main()
{
    dynamic dynamicObject = null;
    object simpleObject = dynamicObject + new AnyClass();
    Console.WriteLine(simpleObject);
}

class AnyClass
{
    public override string ToString()
    {
        return "text";
    }
}

Execution result is:

text

If I understood it correctly, then part dynamicObject + new AnyClass() calls the string concatenation, which return empty string for dynamicObject due to it refers to null, and new AnyClass() returns text. But there's no string argument, which is necessary to call ToString(). Why does it happens so? Why is an exception not being generated about the lack of implementation of the operation '+'?


Solution

  • This is just a matter of operator overload resolution. Since neither null nor AnyClass declare any user-defined operators, the built-in overloads of + are considered. Here is a non-exhaustive list.

    string operator +(string x, string y);
    string operator +(string x, object y);
    string operator +(object x, string y);
    decimal operator +(decimal x, decimal y);
    int operator +(int x, int y);
    long operator +(long x, long y);
    float operator +(float x, float y);
    double operator +(double x, double y);
    

    Since the second parameter is an instance of AnyClass, everything that doesn't take an AnyClass as a second parameter is eliminated, and we are left with:

    string operator +(string x, object y);
    

    Therefore, this is the operator that is called.

    Of course, the results would be different if you declared your own + operators.