Event pattern

In this chapter you will learn:

  1. Get to know C# standard event pattern
  2. Example to use event pattern

C# standard event pattern

C# has a standard event pattern. It defines a standard class to accept the parameters for various events. Event parameter should subclass System.EventArgs to create its own event data.

public class ValueChangedEventArgs : System.EventArgs
{//from j  a  va2 s .c om
    public readonly string str;

    public ValueChangedEventArgs(string str)
    {
        this.str = str;
    }
}

C# provides a generic delegate for the event handler.

public delegate void EventHandler<TEventArgs>(object source, TEventArgs e) 
where TEventArgs : EventArgs;

We should follow the pattern when defining our own event handlers.

Example to use event pattern

using System;// j  a v  a2 s  . c  om

public class ValueChangedEventArgs : System.EventArgs
{
    public readonly string str;

    public ValueChangedEventArgs(string str)
    {
        this.str = str;
    }
}

class Printer
{
    public event EventHandler<ValueChangedEventArgs> ValuesChanged;
    private string stringValue;

    protected virtual void OnPriceChanged(ValueChangedEventArgs e)
    {
        if (ValuesChanged != null)
            ValuesChanged(this, e);
    }


    public string StringValue
    {
        get
        {
            return stringValue;
        }
        set
        {
            OnPriceChanged(new ValueChangedEventArgs(value));
            stringValue = value;
        }
    }
}
class Test
{
    static void stock_PriceChanged(object sender, ValueChangedEventArgs e)
    {
        Console.WriteLine("event!");
    }

    static void Main()
    {

        Printer p = new Printer();

        p.StringValue = "java2s.com";

    }
}

Next chapter...

What you will learn in the next chapter:

  1. What is lambda expressions
Home » C# Tutorial » delegate, lambda, event
delegate
Multicast delegate
delegate variables
delegate parameters
Generic delegate
delegate return
Func and Action
delegate new
chained delegate
Anonymous delegate
delegate array
Return a delegate
delegate as parameter
Event
event multicast
static event
EventHandler
Event pattern
lambda
lambda syntax
Func, Action and lambda
lambda with outer function
lambda iteration variables