What is the 'Object' of these calls?

  • Thread starter Thread starter Peter Oliphant
  • Start date Start date
P

Peter Oliphant

I've written a few event handler methods in my time. Most of them are of the
general form:

void EventHandler( Object^ o, EventArgs^ e )
{
}

However, in all of these I've written, and in every example I've ever seen
on MSDN, the "Object^ o" is NEVER used! What exactly is it, and why is it
there if even MS never seems to use it?

Every example I've seen lists it as 'Object^ /*sender*/', indicating it is
the 'sender' (whatever that means), and it's parameter being commented out
means it doesn't seem like it is ever used. Since it is of type Object^ I'm
guessing it must be typecast to be at all useful.

Most sample code, and everything I've ever written just strips this Object
paramater out or ignores it, and nothing seems to go wrong.

What is it for, and when/how is it useful?

[==Peter==]
 
The Object^ parameter is useful when you handle more than one object with the
same handler. Also it's necessary when the event is raised by an object that is
out of your control (when you don't have a direct controller variable).

Regards
 
Peter Oliphant said:
I've written a few event handler methods in my time. Most of them are of
the general form:

void EventHandler( Object^ o, EventArgs^ e )
{
}

However, in all of these I've written, and in every example I've ever seen
on MSDN, the "Object^ o" is NEVER used! What exactly is it, and why is it
there if even MS never seems to use it?

Every example I've seen lists it as 'Object^ /*sender*/', indicating it is
the 'sender' (whatever that means), and it's parameter being commented out
means it doesn't seem like it is ever used. Since it is of type Object^
I'm guessing it must be typecast to be at all useful.

Most sample code, and everything I've ever written just strips this Object
paramater out or ignores it, and nothing seems to go wrong.

What is it for, and when/how is it useful?

Typically, it is the object you subscribed to. For example:

Button^ b;
b->Clicked += gcnew EventHandler(this, &ClassName::ItWasClicked);

The first argument to ItWasClicked would be b, the Button instance.

Not much use for core logic, but it could be for UI effects. For example:

void LightMeUp(Object^ sender, EventArgs^ a)
{
Control^ c = dynamic_cast<Control^>(sender); // C# "as" operator
if (c != nullptr) {
c->BackColor = Color::Yellow;
}
}

EventHandler^ eIn = gcnew EventHandler(this, &ClassName::LightMeUp);
for each (Control^ c in Controls) {
c->GotFocus += eIn;
c->MouseEnter += eIn;
}
 
Back
Top