Is operator overriding support in C #

I went for an interview, where I was asked to answer the question:

Is operator overriding supported by C #?

I know that operator overloading is supported, but I have no idea how to override the operator. Is it possible?

+4
source share
2 answers

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

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

This is very important to know when writing statements in C #. The statement is bound at compile time. The efficient type that is passed to the operator at run time is not important at all.

Eg. you write a comparison operator

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

And get the following code:

 object myObj1 = new MyClass(); object myObj2 = new MyClass(); if (myObj1 == myObj2) //... 
Object Operator

will be called, not yours, because Arguments are references to an object of type.

+13
source

This is a pretty good article on this. It explains the differences between overloading and overriding, then continues with these definitions for C # statements.

+2
source

Source: https://habr.com/ru/post/1389994/


All Articles