event accessors

  • Thread starter Thread starter Brad Williams
  • Start date Start date
B

Brad Williams

When I try to define accessors for this event, the event invocation
line stops compiling. What's wrong?

public class TestClass
{
public delegate int MyDelegate(string s);
public event MyDelegate myEvent
{
add { Console.WriteLine("myEvent.Add"); }
remove { Console.WriteLine("myEvent.Remove"); }
}
public void Foo(object sender, System.EventArgs e)
{
myEvent("event"); // Compiler error: The event can only
// appear on the left hand side of += or -=
}
}
 
Brad,
When I try to define accessors for this event, the event invocation
line stops compiling. What's wrong?

By using the explicit accessor syntax, you no longer get the
underlying delegate auto generated by the compiler. So you have to add
a MyDelegate field yourself and add/remove handlers to it inside the
add and remove accessors.



Mattias
 
Back
Top