event accessors

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 -=
}
}
 
M

Mattias Sjögren

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top