Question

I have a method

protected void Item_Click(object sender, EventArgs e)
{     }

I wanted that other code to call this method. ( didn't really need the sender nor e)

something like :

Item_Click(null, null)

But then I remembered I can use EventArgs.Empty instead.

Mouse hovering over it shows :

enter image description here

Wait...What ?

EventArgs.Empty represents an event ? it is not. it should represent empty argument not an event.

just like string.empty represent empty string.

  • Am I missing something here?
Was it helpful?

Solution

It's just poor documentation, conflating two concepts in one word. The latest documentation seems a little better:

Provides a value to use with events that do not have event data.

The trouble is that "an event" has two separate meanings:

  • The event that you can subscribe to
  • A single "instance" of that event being raised

For example, it wouldn't be unreasonable to say: "Subscribe to the KeyPress event to receive keyboard-related events."

(The word "delegate" is just as bad, used to describe delegate types and instances of them.)

It's all unfortunate, but rest assured that you have the right idea.

As an aside, if you want to call the method other than when the event is raised, I'd potentially separate it into two methods:

// This only exists to handle the event, delegating to the DoSomething method
private void HandleItemClicked(object sender, EventArgs e)
{
    DoSomething();
}

// This can be called from other code, and should be named according to what it
// does.
private void DoSomething()
{
}

If you're subscribing to the event manually, you don't even need the extra method:

item.Click += delegate { DoSomething(); };

This way you make it clear that your "real" method doesn't care about the sender or event args, and you don't need to provide "dummy" values when calling it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top