Syed Musa Ali
Syed Musa Ali

Reputation: 35

Operator overloading in C#

I was a bit confused with Operator overloading in C# language, Can you Please tell me is Operator overloading static or dynamic in nature.

Upvotes: 2

Views: 477

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500525

If you mean "is it polymorphic or not?" then the answer is no - operators are found statically by the C# compiler, unless you're using the dynamic type. For example, consider this code:

using System;

class Test
{    
    static void Main(string[] args)
    {
        string x = "hello";
        string y = new string(x.ToCharArray());        
        Console.WriteLine(x == y); // True

        object ox = x;
        object oy = y;
        Console.WriteLine(ox == oy); // False

        dynamic dx = x;
        dynamic dy = y;
        Console.WriteLine(dx == dy); // True
    }
}

The first call to == uses the operator declared in string, as the compiler knows that both operands are of type string. It compares the two character sequences, finds they're equal, and returns True.

The second call to == uses the operator declared in object because the compile-time types of the expressions ox and oy are object. This operator only compares references. The references are different (they refer to different values), so this returns False. Note that in this case the values of ox and oy will refer to strings at execution time, but that isn't taken into account when the compiler decides which overload to call. (It only knows of ox and oy as being of type object.)

The third call to == uses dynamic typing to discover the operator at execution time, using the actual types of the references, rather than the compile-time types of the expressions. This discovers the overload in string, and so again the operator returns True.

Upvotes: 11

CloudyMarble
CloudyMarble

Reputation: 37566

The basic Operator Overloading is static:

public static SomeClass operator ++(SomeClass arg)

Try this Series showing some examples

Upvotes: 0

Related Questions