CPJoshi
CPJoshi

Reputation: 487

C# reflection: How to get a private event?

Is it possible to get the private event of a class using reflection? the below code fails to get the event:

//class having a private Event.
public class Sample
{
    private delegate void MyDelegate(string ip4);
    private event MyDelegate MyEvent;
}

internal class Program
{
    private static void Main(string[] args)
    {
        //try getting the non-public event
        EventInfo[] events = typeof (Sample).GetEvents(BindingFlags.NonPublic);
        Console.WriteLine(events.Length); //it's 0
        var evt = typeof (Sample).GetEvent("MyEvent", BindingFlags.NonPublic); //evt is null
    }
}

Upvotes: 0

Views: 665

Answers (2)

Kevin Holditch
Kevin Holditch

Reputation: 5303

var evt = typeof(Sample).GetEvent("MyEvent", BindingFlags.NonPublic | BindingFlags.Instance);

Upvotes: 1

Selman Genç
Selman Genç

Reputation: 101681

You need also specify BindingFlags.Instance ..

var evt = typeof (Sample)
  .GetEvent("MyEvent", BindingFlags.NonPublic | BindingFlags.Instance); //evt is null

Upvotes: 8

Related Questions