C# to IL 5 Operator Overloading(操作符重载)

时间:2021-08-05 08:45:11

Every operator overload that we use in C#, gets converted to a function call in IL. The
overloaded > operator translates into the function op_GreaterThan and a + gets converted
to op_Addition etc. In the first program of this chapter, we have overloaded the + operator
in class yyy to facilitate adding of two yyy objects.

While using the plus (+) operator on the two yyy objects, C# is aware that IL does not
support operator overloading. Therefore, it creates a function called op_Addition in the
class yyy.
Thus, operator overloading gets represented as a mere function call. The rest of the code is
easy for you to figure out.
In IL, there is no rule stating that if the > operator is overloaded, then the < operator also
has to be overloaded. These rules are imposed by the C# compiler, and not by IL since, IL
does not support the concept of overloading at all.

The C# compiler is extremely intelligent. Whenever a yyy object has to be converted to a
string, it first checks for the presence of an operator called string in the class yyy. If it
exists, it calls that operator.
The operator named string is a predefined data type in C#. Hence, it is converted into the
operator op_Implicit. This operator takes a yyy object as a parameter. It returns a string on
the stack for the WriteLine function. The ToString function is not called.
C# will generate an error if you alter even a single parameter to the operator string, but
such is not a case with IL as it does not support operator overloading and conversions

In the C# code above, we have dispensed with the operator string and instead, have used
the ToString function. As usual, we put the object a on the stack. In the IL code given
earlier, due to the presence of operator overloads in the C# code, the function op_Implicit
was called. In this case, since there are no operator overloads, the object reference to object
a is simply put on the stack. In class yyy, even though, the function ToString is not
explicitly called, the function does get executed.
Since the ToString is virtual in the class Object, at run time, the ToString function is called
from the class yyy, instead of being called from the class Object. This is due to the concept
of a vtable, where all virtual function addresses reside.
If the word virtual is removed from the function, the ToString function gets called from the
class Object instead of the class yyy

In the above code, we have cast a yyy object into a string using an explicit cast. IL does not
understand C# keywords like implicit or explicit. It converts the cast to an actual function
such as op_Explicit or op_Implicit. Thus writing a C# compiler requires a lot of grey matter.