Strange error - register 2 methods with a different event signature

I found weird behavior in C #.

See an 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 Error at last registration.

Section 2 and 3 Succeed.

Why is this happening?

I think the first section is a serious mistake! Since the last registration event failed, despite the fact that the signature method is compatible with one hundred percent!

+4
source share

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


All Articles