4

I am testing Console application on Reflection to call the delegate whose access modifier is private. The code looks like this:

    public class EventPublisher
    {
        private delegate void PrivateDelegate(string message);
        public delegate void PublicDelegate(string message);
    }

    public class PrivateDelegateSubscriber
    {
        public void Subscribe(EventPublisher evPub)
        {
            Type t = typeof(EventPublisher);
            MemberInfo[] privateDelegate = t.GetMember("PrivateDelegate", BindingFlags.NonPublic);

            Delegate delByReflection = Delegate.CreateDelegate((System.Type)privateDelegate.GetValue(0), this, "MethodForPrivateDelegate");
            // how to call the private delegate like public delegate below?

            Delegate delByReflection2 = Delegate.CreateDelegate(typeof(EventPublisher.PublicDelegate), this, "MethodForPrivateDelegate");
            EventPublisher.PublicDelegate delByReflection2_ins = (EventPublisher.PublicDelegate)delByReflection2;
            delByReflection2_ins("test public delegate");
        }

        public void MethodForPrivateDelegate(string message)
        {
            Console.WriteLine("This is from private delegate subscriber, writing: " + message);
        }
    }

I have tested the public delegate and it is working as expected, but I haven't found any way to do it on private delegate. My question is the commented code above if there is any way to do it, or the reason why it is not possible.

Thanks in advance

xdrnc
  • 260
  • 2
  • 11
  • 1
    Do you "need" to cast? Is just calling `DynamicInvoke` on the delegate insufficient? Also, somewhat obviously, what's the *point*? In both scenarios, you're creating a delegate just to then, effectively, be calling code you already have access to (`MethodForPrivateDelegate`) – Damien_The_Unbeliever May 02 '17 at 07:00
  • I have updated it to use "call" instead. It is working with DynamicInvoke. The method to be called here is the simplified testing only.Thanks – xdrnc May 02 '17 at 07:26

1 Answers1

2

how to cast to private delegate like public delegate below?

You don't. A cast is a compile-time declaration, requiring access to the type in question. It is impossible to declare a variable having a type that is not accessible to the code in which you are trying to declare the variable.

You can, however, still invoke such a delegate, using the DynamicInvoke() method. E.g.:

delByReflection.DynamicInvoke("test private delegate");
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136