0
votes

I need to access x and y properties of object obj(of type some ClassA) in the event handling method subscribed to an event in object obj.

Option1: Just make this event of type EventHandler, cast the sender.

void handlingMethod(object sender, EventArgs e)
{
    ClassA ca = sender as ClassA;
    Dosomething(ca.id, ca.x, ca.y);
}

RaiseEvent(this,null); //in ClassA

Option2: Make a SpecialEventHandler1 so that casting can be avoided.

void handlingMethod(SpecialEventArgs e)
{
    Dosomething(e.id, e.x,e.y);
}

RaiseSpecialEvent1(new SpecialEventArgs(this.id, this.x,this.y));//in ClassA

Option3: Make a SpecialEventHandler2 so that both casting and new SpecialEventArgs object creation can be avoided.

void handlingMethod(ClassA sender)
{
     Dosomething(sender.id, sender.x, sender.y);
}
RaiseSpecialEvent2(this); //in ClassA

Lets say this events are raised continuously @50/sec. Which one is more efficient? Does it depend on size of ClassA? I am assuming that Option3 is the best way in terms of performance. Please give your insights.

1

1 Answers

3
votes

50hz is not fast at all so your best bet is to stick with convention. This will make your code more approachable to new developers. Also remember to use a cast when you expect only one type so you can get a detailed exception if the event is raised incorrectly.

void MyClassA_Something(object sender, EventArgs e)
{
    ClassA ca = (ClassA)sender;
    Dosomething(ca.id, ca.x, ca.y);
}

Events really shouldn't take too long but if they do you really need to offload it onto another thread. In either case though you should stick with the convention for events.

void MyClassA_Something(object sender, EventArgs e)
{
    ThreadPool.QueueUserWorkItem(o => {
        ClassA ca = (ClassA)sender;
        Dosomething(ca.id, ca.x, ca.y);
    });
}