Why can’t I use the event declared in Base from Sub?
class Program
{
static void Main(string[] args)
{
Sub sub = new Sub();
sub.log += new Base.logEvent(sub_log);
sub.go();
}
static void sub_log(string message, int level)
{
Console.Out.WriteLine(message + " " + level);
}
}
public abstract class Base
{
public delegate void logEvent(String message, int level);
public event logEvent log;
}
public class Sub : Base
{
public void go()
{
log("Test", 1); // <-- this won't compile
}
}
Events may only be invoked from the class that declares them.
From outside of the definition of a class (even in a derived class) you can only register and unregister from an
event. Inside of the class, the compiler only allows you to raise the event. This is a by-design behavior of C# (which actually changes slightly in C#4 – Chris Burrows describes the changes on his blog).What you want to do here is provide a
RaiseLogEvent()method in the base class, which would allow the derived class to invoke this event.As an aside, you should consider using the
EventHandler<>delegate type, rather than creating your own event types when possible.