Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Operator Overriding supported by C#

Tags:

c#

overriding

I have gone to an interview where I was asked to answer a question:

Is operator overriding supported by C#?

I know that operator overloading is supported but I have no idea about overriding a operator. Is it possible?

like image 398
शेखर Avatar asked Jan 09 '12 05:01

शेखर


1 Answers

No, operator overriding is not supported. The term Overriding is used when a method is inherited by a subclass and the subclass overrides it with its own implementation. Operators are all static in C# and cannot be overridden.

Overloading means that another method with the same name but a different signature (arguments) is defined. That's what you can do with operators.

This is extremely important to know when writing operators in C#. The operator is bound at compile time. The effective type which is passed to the operator at runtime is not important at all.

Eg. you write some comparison operator

public static bool operator==(MyClass c1, MyClass c2)
{
  //...
}

And have the following code:

object myObj1 = new MyClass();
object myObj2 = new MyClass();

if (myObj1 == myObj2)
//...

object's operator will be called, not your own, because the arguments are references of type object.

like image 169
Stefan Steinegger Avatar answered Oct 06 '22 00:10

Stefan Steinegger