Late bound event w/o overhead when firing

interface IDynamicEvents  
{ 
    bool Subscribe(MulticastDelegate eventHandler, string eventName); 
    bool Unsubscribe(MulticastDelegate eventHandler, string eventName); 
} 

abstract class DynamicEventsBase : IDynamicEvents  
{ 
    #region Private 
    private WeakReference _wrEventDictionary = new WeakReference(null); 

    private SortedDictionary<string, EventInfo> EventDictionary 
    { 
        get 
        { 
            SortedDictionary<string, EventInfo> eventDictionary = _wrEventDictionary.Target as SortedDictionary<string, EventInfo>; 
            if (eventDictionary == null) 
            { 
                _wrEventDictionary.Target = eventDictionary = new SortedDictionary<string, EventInfo>(StringComparer.Ordinal); 
                foreach (EventInfo ei in GetType().GetEvents(BindingFlags.Instance  BindingFlags.Public)) 
                    eventDictionary.Add(ei.Name, ei); 
            } 
            return eventDictionary; 
        } 
    } 
    #endregion 

    #region IDynamicEvents Members 
    public bool Subscribe(MulticastDelegate eventHandler, string eventName) 
    { 
        EventInfo ei = EventDictionary[eventName]; 
        if (ei != null) 
        { 
            ei.AddEventHandler(this, eventHandler); 
            return true; 
        } 
        return false; 
    } 

    public bool Unsubscribe(MulticastDelegate eventHandler, string eventName) 
    { 
        EventInfo ei = EventDictionary[eventName]; 
        if (ei != null) 
        { 
            ei.RemoveEventHandler(this, eventHandler); 
            return true; 
        } 
        return false; 
    } 
    #endregion 
}
Google
m@kli.dk @klinkby RSS feed  GitHub