Why my custom event in C# is not raised?
-
29-10-2019 - |
Question
It's not the first time I've created a Custom Event in C#. It boggles my mind why it doesn't work in this simple case.
I have a Publisher with Subscribers. In my main program, I instantiated 1 publisher and 2 subscribers. When addNews is called, Subscribers should receive the event NewPublication:
static void Main()
{
Publisher publisher = new Publisher();
Subscriber subscriber1 = new Subscriber("John");
Subscriber subscriber2 = new Subscriber("Jane");
publisher.AddNews("custom event NewPublication");
}
In subscriber.cs I have:
public delegate void NewPublication(Publisher fromPublisher, String Message);
public class Publisher {
private List<String> newsList = new List<String>();
public event NewPublication newPublication;
public void AddNews(String news) {
newsList.Add(news);
if (newPublication != null)
{
newPublication(this, news);
}
}
}
In Subscriber I have:
private String m_Name;
private event NewPublication newPublication;
public Subscriber(String name) {
m_Name = name;
newPublication += new NewPublication(subscriber_newPublication);
}
public void subscriber_newPublication(Publisher fromPublisher, String Message) {
MessageBox.Show(m_Name + " is notified for " + Message);
}
It compiles, but when running, the event is never raised. Why not? How can I fix my code so that it does get raised?
What's really different from MSDN sample code: http://msdn.microsoft.com/en-us/library/w369ty8x.aspx
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow