0

I am new to C# and programming in general and am trying to figure out how to use events. Previously I have been programming with ActionScript3, and there events are a special class that you inherit from if you want to create your own events, and then that event can be called by any other class.

With C# I have tried to do something similar, like so:

public class EventManager
{
    public delegate void TempDelegate();
    public static event TempDelegate eSomeEvent;
}

public class SomeOtherClass
{
    //doing some stuff, then:
    if (EventManager.eSomeEvent != null)
    {
        EventManager.eSomeEvent();
    }
}

This gives me a compiler error CS0070: The event 'EventManager.eSomeEvent' can only appear on the left hand side of += or -= (except when used from within the type 'EventManager')

The information about this error over on the msdn indicates that I should use += instead of trying to call the event, but I don't really understand this. I'm not trying to subscribe anything from SomeOtherClass to the event delegate, I am just trying to call this event so that it starts executing those functions that are already subscribed to that event.

So is it possible to do it this way? If not, is it at all possible to call an event that is of one class, from another class? I simply wish to reuse certain events in my classes rather than creating many similar ones in multiple classes.

Any advice with this would be greatly appreciated!

Garry Wong
  • 793
  • 2
  • 8
  • 23
  • I'm a little unclear. Do you want to bubble up events from one class and pass them through another class (that has that class)? Or are you just trying to copy events across multiple classes (like an event library)? – SQLMason Dec 25 '13 at 02:56
  • 1
    http://stackoverflow.com/questions/756237/c-raising-an-inherited-event – SQLMason Dec 25 '13 at 02:57

2 Answers2

4

You can wrap the event call in a public method and use that from your other classes.

public void OnSomeEvent()
{
    var handler = eSomeEvent;
    if (handler != null) handler(this, null);
}

However you might want to look at the design again, if you are really sure the event should be on a different class than the one triggering it.

Jesper Fyhr Knudsen
  • 7,802
  • 2
  • 35
  • 46
1

Well, the typical solution is to put eSomeEvent invocation into the EventManager class

public class EventManager
{
    public delegate void TempDelegate();
    public static event TempDelegate eSomeEvent;

    // Not thread safe as well as your code
    // May be internal, not public is better (if SomeOtherClass is in the same namespace) 
    public static void PerformSomeEvent() {
      if (!Object.ReferenceEquals(null, eSomeEvent)) 
        eSomeEvent(); // <- You can do it here
    }
}

public class SomeOtherClass
{
    //doing some stuff, then:
    EventManager.PerformSomeEvent();
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215