Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit method group conversion gotcha (Part 2)

Simplified from this question and got rid of possible affect from LinqPad(no offsensive), a simple console application like this:

public class Program
{
    static void M() { }    
    static void Main(string[] args)
    {
        Action a = new Action(M);
        Delegate b = new Action(M);
        Console.WriteLine(a == b);      //got False here
        Console.Read();
    }        
}

The "false" results from the operator ceq in CIL of the code above(visit the original question for details). So my questions are:

(1) Why == is translating to ceq instead of call Delegate Equals?

Here I don't care about the (un)wrapping between Delegate and Action. At the very last, when evaluating a == b, a is of type Action while b is a Delegate. From the spec:

7.3.4 Binary operator overload resolution

An operation of the form x op y, where op is an overloadable binary operator, x is an expression of type X, and y is an expression of type Y, is processed as follows:

• The set of candidate user-defined operators provided by X and Y for the operation operator op(x, y) is determined. The set consists of the union of the candidate operators provided by X and the candidate operators provided by Y, each determined using the rules of §7.3.5. If X and Y are the same type, or if X and Y are derived from a common base type, then shared candidate operators only occur in the combined set once.

• If the set of candidate user-defined operators is not empty, then this becomes the set of candidate operators for the operation. Otherwise, the predefined binary operator op implementations, including their lifted forms, become the set of candidate operators for the operation. The predefined implementations of a given operator are specified in the description of the operator (§7.8 through §7.12).

• The overload resolution rules of §7.5.3 are applied to the set of candidate operators to select the best operator with respect to the argument list (x, y), and this operator becomes the result of the overload resolution process. If overload resolution fails to select a single best operator, a binding-time error occurs.

7.3.5 Candidate user-defined operators

Given a type T and an operation operator op(A), where op is an overloadable operator and A is an argument list, the set of candidate user-defined operators provided by T for operator op(A) is determined as follows:

• Determine the type T0. If T is a nullable type, T0 is its underlying type, otherwise T0 is equal to T.

• For all operator op declarations in T0 and all lifted forms of such operators, if at least one operator is applicable (§7.5.3.1) with respect to the argument list A, then the set of candidate operators consists of all such applicable operators in T0.

• Otherwise, if T0 is object, the set of candidate operators is empty.

• Otherwise, the set of candidate operators provided by T0 is the set of candidate operators provided by the direct base class of T0, or the effective base class of T0 if T0 is a type parameter.

From the spec, a and b have a same base class Delegate, obviously the operator rule == defined in Delegate should be applied here(the operator == invokes Delegate.Equals essentially). But now it looks like the candidate list of user-defined operators is empty and at last Object == is applied.

(2) Should(Does) the FCL code obey the C# language spec? If no, my first question is meaningless because something is specially treated. And then we can answer all of these questions using "oh, it's a special treatment in FCL, they can do something we can't. The spec is for outside programmers, don't be silly".

like image 489
Cheng Chen Avatar asked Jan 20 '12 09:01

Cheng Chen


2 Answers

Compiler works very different and unusual with delegates. There are a lot of implicit handling. Notice, that 'common base type' rule in this guide is applied to 'user-defined operators'. Delegates are internal and system. For example, you can write Action a = M; instead of Action a = new Action(M);. And you can add a += M; after that. Check what happens in CIL, it is interesting at a first time.

Further more: it is dangerous and non-trivial to compare delegates. Every delegate is actually multicast delegate. You can add several function pointers to the same delegate. Does delegates [L(); M(); N();] equals to delegate [M();] ? Function pointer contains class instance (for instance method). Does [a.M();] equals to [b.M();]? All that depends on a case, and comparison implementation requires to step through invocation list.

Delegates inheritance from common base type Delegate is implicit and this problem you can face in another scenarios, e.g. generic constraint: you can not specify Delegate as a constraint to generic parameter T. Here compiler explicitly declines this. The same about creating your own classes, inherited from Delegate.

This is answer to both questions - 'Delegate' is not purely FCL, it is tightly coupled with compiler. If you really want Microsoft's delegate comparer behavior - just call explicitly Equals(a, b)

like image 102
Dmitry Gusarov Avatar answered Oct 23 '22 03:10

Dmitry Gusarov


warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'System.Action'

That is the warning you get for that C# code. Don't ignore that warning, the C# team was well aware that the code they generated for this comparison was unexpected. They didn't have to generate that code, they could easily have done what you expected. Like this code does:

Module Module1
    Sub M()
    End Sub

    Sub Main()
        Dim a = New Action(AddressOf M)
        Dim b = DirectCast(New Action(AddressOf M), [Delegate])
        Console.WriteLine(a = b)      ''got True here
        Console.Read()
    End Sub
End Module

Which generates almost the same MSIL, except that instead of ceq you get:

 IL_001d:  call bool [mscorlib]System.Delegate::op_Equality(class [mscorlib]System.Delegate,
                                                            class [mscorlib]System.Delegate)

Which what you hoped the C# code would do. That was VB.NET code, in case you didn't recognize it. Otherwise the reason that Microsoft keeps two major managed languages around, even though they have very similar capabilities. But with very different usability choices. Whenever there was more than one way to generate code, the C# team consistently chose for performance, the VB.NET team consistently for convenience.

And performance certainly is the key here, comparing delegate objects is expensive. The rules are spelled out in Ecma-335, section II.14.6.1. But you can reason it out for yourself, there is a lot of checking to do. It needs to check if the delegate target object is compatible. And for each argument it must check if the value is convertible. Expense that the C# team does not want to hide.

And doesn't, you get the warning to remind you that they made the unintuitive choice. .

like image 5
Hans Passant Avatar answered Oct 23 '22 03:10

Hans Passant