Mohammad Fajar
Mohammad Fajar

Reputation: 1007

Why We Need EventArgs class in C#?

I know that the purpose of event keyword just to used in pair with += operator to make list of delegate. And when constructing delegate we can make any signature (of parameter) for method that compatible with that delegate.

For example I create delegate

public delegate void StartEventHandler(object sender, StartEventArgs e);

with two parameter: the first with the type object and the second with the type StartEventArgs. But in many article that I found on the internet, the second parameter for that delegate must inherited EventArgs type. Why we do this instead to make the second parameter come/inherited from arbitrary type?

Upvotes: 0

Views: 391

Answers (1)

Sean Dawson
Sean Dawson

Reputation: 5786

You don't need to and I'm sure the code will still compile if you used an arbitrary base class but it is a convention.

Conventions are good because it makes it easier to understand for people who are not familiar with your code already. If I subscribe to an event in C# I expect a certain method signature.

It is also good because it makes different types of events interchangeable.

For example, say you have three delegates

public delegate void AEventHandler(object sender, AEventArgs e);
public delegate void BEventHandler(object sender, BEventArgs e);
public delegate void CEventHandler(object sender, CEventArgs e);

You could write a generic method that conforms to all three delegates because all the args objects inherit from the same base class.

public void eventMethod(object sender, EventArgs e) {
    // Any one of the events fired
}

public void subscribeToEvents() {
    eventA += new AEventHandler(this.eventMethod);
    eventB += new BEventHandler(this.eventMethod);
    eventC += new CEventHandler(this.eventMethod);
}

And even cast if you know what types to expect

public void eventMethod(object sender, EventArgs e) {
    // Any one of the events fired
    if (e is BEventArgs) {
        // Event type B fired
        var eventB = e as BEventArgs;
        eventB.doSomething()
    }
}

Upvotes: 4

Related Questions