Link to home
Start Free TrialLog in
Avatar of Hob_Nob
Hob_Nob

asked on

Event handling and communication between two classes

Hi all,
Ive tried to simplify what my problem is, and its probably straight forward Delegate/Event stuff, but I havent really got the hang of that yet!!

I have two classes, say, class A and class B
Class B has a private member variable called myString = "Hello"

using an Event in Class A, I want to call an EventHandler in class B, which returns the word "Hello" back to Class A.  But how is this done???

Avatar of bigjim2000
bigjim2000

Can't you do this with a property?  If all you need is to return a private member variable, then just create a public property in your B class that returns the string.

Events are more for telling an object they need to do some processing.  It is helpful to think of your object as a real-world-object, for example, a car.  The car would have properties, for example, like color, current speed, engine type, etc.  But it would have events for things such as StartEngine (to initialize the engine "object", and stuff like that), ApplyBrakes, etc.

I hope this is clear.  I suppose what I'm trying to say, is that the Event would take the place of calling a public method.  This is a very simplified view of what events do, but I hope it is a start for you.

-Eric
I should also mention what delegates ARE, just in case that IS what you want to use.

Delegates are just function pointers... essestially moveable references to methods in your object.  For example, your object B might have an event for, say, StringChanged.  You could then tell your object A to have an EventHandler to trap the StringChanged event in object B.  That way, you could tell your object A to get the new string from B whenever it changes, without having to CHECK all the time if it has changed.

Hope this is more of a clarification.

-Eric
ASKER CERTIFIED SOLUTION
Avatar of NipNFriar_Tuck
NipNFriar_Tuck

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Hob_Nob

ASKER

I got it working based around what NipFriar_Tuck was saying, so thank you Friar Tuck.
Looking back at my problem, I wanted an listener class to await for an event to be fired from a GUI button.

Class A:

ClassB classB = new ClassB();
classB.MyEvent += new EventHandler(fireEvent);

private void fireEvent(object sender, EventArgs e)
{
       MessageBox.Show("Class B just fired an event!!!!!");
}

Class B:

private event EventHandler myEvent;
public event EventHandler MyEvent
{
    add
    {myEvent+=value;}
     remove
    {myEvent-=value;}
}

//Event insantiation:
private void button1_Click_1(object sender, System.EventArgs e)
{  onMyClick(sender, e); }

protected virtual void onMyClick(object sender, EventArgs e)
{
     if(myEvent!=null)
          myEvent(this, EventArgs.Empty);
}