With operator overloading, how does the C # compiler determine which implementation is used with mixed-type operands?

int normal; int? nullable; var x = normal/nullable; // expression evaluates to Nullable<int> var y = nullable/normal; // also Nullable<int> 

EDIT: My original question was a bit appealing for the answers I am not looking for. The title actually summarizes the question, and the example used to illustrate it was poorly chosen.

In the above example, there is only one possibility for the compiler: the operator int.divide does not support nulled int operands int, int? does, and that solves it. There is no ambiguity and there is no need for any presentation rules.

But what if I have two types that overload the same operator, say, separate for example, and both support the other type as one of the operands?

There are two questions here:

1) How does the compiler decide whether to use an operator from Type1 or Type2 if both types support Type1 / Type2 and Type2 / Type1? Is there priority from left to right (for binary operations) or something else?

2) Are there any assumptions about operations such as symmetry? In other words, is A + B always equal to B + A, or is it up to type?

In the end, these questions, perhaps a little academic, as in many practical scenarios, any taste of the method (whether it be virtual methods, ordinary instance methods or static "utilty" methods, even if the latter closely resembles the operator) can be used to same end. Again, there may be cases where there is a real value that can be obtained by including syntax with much easier to read that result from using operators instead of the usual method syntax. (Syntax is the only reason that languages ​​have operators, primarily this is just a method.)

+4
source share
1 answer

how does the compiler decide that it is a division operator of type NULL and not the regular int operator that is used?

Because the "normal" operator cannot be applied.
This, of course, uses the usual operators:

  var x = normal/nullable.Value; 

But when you combine normal and nullable, consider nullable to be unknnown. How much is x + unknown ? This is again unknown. And since the result can be null , the result type of the expression must be null.

+2
source

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


All Articles