4

I've found strange behavior in C#.

Look at the example below:

namespace ConsoleApplication1
{
    class MyClass
    {
        public event Action<MyClass> Event;
        public void OnEvent(MyClass arg) { }
        public void OnEventObject(object arg) { }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                MyClass myClass = new MyClass();
                myClass.Event += (Action<object>)myClass.OnEventObject; // Succeed.
                myClass.Event += myClass.OnEvent; // ArgumentException: Delegates must be of the same type.
            }
            catch { Console.WriteLine("Section 1 failed!"); }

            try
            {
                MyClass myClass = new MyClass();
                myClass.Event += myClass.OnEvent; // Succeed.
                myClass.Event += (Action<object>)myClass.OnEventObject; // ArgumentException: Delegates must be of the same type.
            }
            catch { Console.WriteLine("Section 2 failed!"); }

            try
            {
                MyClass myClass = new MyClass();
                myClass.Event += myClass.OnEvent; // Succeed.
                myClass.Event += myClass.OnEventObject; // Succeed.
            }
            catch { Console.WriteLine("Section 3 failed!"); }

            try
            {
                MyClass myClass = new MyClass();
                myClass.Event += myClass.OnEventObject; // Succeed.
                myClass.Event += myClass.OnEvent; // Succeed.
            }
            catch { Console.WriteLine("Section 4 failed!"); }
        }
    }
}

Section 1 and 2 Failed on the last Registration.

Section 2 and 3 Succeed.

Why does it happen?

I think the first section Is severe bug! Because the last registration event failed despite the signing method is compatible with hundred percent!

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
fiaharon
  • 391
  • 3
  • 6
  • 1
    @cFrozenDeath You mean, as they've already done in the MyClass declaration at the top? =) – J. Steen Jul 20 '16 at 11:29
  • @cFrozenDeath: Read the question from the start. – fiaharon Jul 20 '16 at 11:29
  • 3
    This *should* be marked as a duplicate of this question: http://stackoverflow.com/questions/2306814/co-and-contravariance-bugs-in-net-4-0 . That said, I'm not going to close it. The original question is 6 years old so I kinda wish Eric Lippert sees the new one and gives us an explanation of why it couldn't be fixed – Kevin Gosse Jul 20 '16 at 11:35

0 Answers0