Been trying to learn c# and trying out events. Have tried it out, and got SOMETHING to function. When looking at my code it looks odd, because I have to create new objects for each subscriber, and then subscribe to the publisher. Do I need to create new object, and then subscribe to the publisher with that object?
Program.cs
namespace ConsoleApp1
{
class Program
{
public static void Main()
{
ExternalClass potato = new ExternalClass();
potato.Start();
}
}
}
Externalclass.cs
using System;
namespace ConsoleApp1
{
class ExternalClass
{
//This is the event, which is the actual event you call to trigger all of the other method/function calls.
public void Start()
{
string SubscribeMessage = "Subscribing...";
string UnsubscribeMessage = "Unsubscribing";
Apple potato = new Apple();
Orange beet = new Orange();
//adding a function to an event
Console.WriteLine(SubscribeMessage);
potato.MyEvent += potato.helloWorld;
potato.MyEvent += beet.DisplayOrange;
potato.OnEventSuccess();
//unsubscribing from an event
Console.WriteLine(UnsubscribeMessage);
potato.MyEvent -= beet.DisplayOrange;
potato.MyEvent -= potato.helloWorld;
potato.OnEventSuccess();
}
}
}
Apple.cs
using System;
namespace ConsoleApp1
{
class Apple
{
public event Action MyEvent;
//This is the function that you wish to call when you call the event. All other function/method calls must have the same shape as the delegate
public void helloWorld()
{
Console.WriteLine("Hello world!");
}
public void OnEventSuccess()
{
//myEvent?.Invoke();
if (MyEvent != null)
{
MyEvent?.Invoke();
}
else
{
Console.WriteLine("Event is empty!");
}
}
}
}
Orange.cs
using System;
namespace ConsoleApp1
{
public class Orange
{
public void DisplayOrange()
{
Console.WriteLine("Orange is functioning");
}
}
}
Sample output:
Subscribing...
Hello world!
Orange is functioning
Unsubscribing
Event is empty!