Designing a type which exposes an event p.1

1. How to define a class which will hold data?

2. How to define an event?

3. How to define a method which will call the event?

4 How to define a method which will call the event?

5. How to define a method which will send data for the event.

             

The first step is defining a class which will hold data that should be sending to receivers. The class must be derived from the System.EventArgs class.

 

Example 1:

    public class MyEventArgs<T> : System.EventArgs

    {

        private T _data;

 

        public T Data

        {

            get { return _data; }

        }

 

        public MyEventArgs(T data)

        {

            _data = data;

        }

    }

 

The System.EventArgs is defined as:

 

Example 2:

    // The base class for all event classes.

 [Serializable]

[System.Runtime.InteropServices.ComVisible(true)]

    public class EventArgs {

        public static readonly EventArgs Empty = new EventArgs();

   

        public EventArgs()

        {

        }

    }

 

The second step is defining an event  

 

public static event EventHandler<MyEventArgs<Object>> NewEvent;

 

, where EventHandler is defined as

               

[SerializableAttribute]

public delegate void EventHandler<TEventArgs>( Object sender, TEventArgs e) where TEventArgs : EventArgs

 

and the method prototype must look like:

 

private void CallbackMethod(Object sender, MyEventArgs<Object> args)

 

The first parameter sender has Object type instead of the type where the event was defined, because of the inheritance. If the class will be inherited then its event will be inherited too. So we need casting anyway.

In case when the event doesn’t need to send any additional information we can use the EventArgs.Empty as the second parameter.

The delegate prototype doesn’t return value, because the event can have more then one registered callback methods and it’s impossible to get return value from all of them.

 

            Define a method which will call the event. We need to create a temporary variable when a thread unregisters from event after the null checking to avoid the NullReferenceException. It works because delegates are immutable types.

 

Example 3:

 

        protected virtual void OnNewEvent(MyEventArgs<Object> eventArgs)

        {            

            EventHandler<MyEventArgs<Object>> tempEvent = NewEvent;

           

            if (tempEvent != null)

                tempEvent(this, eventArgs);

        }

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s