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?
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.
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