Reputation: 53
There are 3 classes A, B, C(Consumer). Class A calls B to fire event so that Class C can receive as it has subscribed. How to achieve this functionality?
Below is the code.
public delegate void TestDelegate();
public class B
{
public event TestDelegate TestEvent;
public B()
{
}
public void Fire()
{
TestEvent();//Null reference exception as not subscribed to the event as TestEvent is always null
}
}
public class A
{
static void Main()
{
B b = new B();
b.Fire(); //Null reference exception as not subscribed to the event.
}
}
//Consumer application
public Class C
{
static void Main()
{
B b = new B();
b.TestEvent+= new TestDelegate(c_TestEvent);
}
static void c_TestEvent()
{
Console.WriteLine("Console 2 Fired");
}
}
Upvotes: 1
Views: 45
Reputation: 897
Here's how to do it if you use the same instance of B:
using System;
namespace StackOverflow_Events
{
class Program
{
static void Main(string[] args)
{
B b = new B();
A a = new A(b);
C c = new C(b);
a.Test();
Console.ReadKey();
}
}
public delegate void TestDelegate();
public class B
{
public event TestDelegate TestEvent;
public B()
{
}
public void Fire()
{
TestEvent?.Invoke();
}
}
public class A
{
private B b;
public A(B _b)
{
b = _b;
}
public void Test()
{
b.Fire();
}
}
//Consumer application
public class C
{
private B b;
public C(B _b)
{
b = _b;
b.TestEvent += new TestDelegate(c_TestEvent);
}
static void c_TestEvent()
{
Console.WriteLine("Console 2 Fired");
}
}
}
Here's how to do it statically:
using System;
namespace StackOverflow_Events
{
class Program
{
static void Main(string[] args)
{
C.Init();
A.Test();
Console.ReadKey();
}
}
public delegate void TestDelegate();
public class B
{
public static event TestDelegate TestEvent;
public B()
{
}
public void Fire()
{
TestEvent?.Invoke();
}
}
public class A
{
public static void Test()
{
B b = new B();
b.Fire();
}
}
//Consumer application
public class C
{
public static void Init()
{
B.TestEvent += new TestDelegate(c_TestEvent);
}
static void c_TestEvent()
{
Console.WriteLine("Console 2 Fired");
}
}
}
Upvotes: 0
Reputation: 136164
Just ensure TestEvent
is not null
public void Fire()
{
if(TestEvent != null)
TestEvent();
}
The newer way to do this using the safe navigation operator ?.
public void Fire()
{
TestEvent?.Invoke();
}
Upvotes: 1
Reputation: 539
There are multiple issues with your code
Refactor your code such that there is only one entry point into your application and also have one instance of B which will be used to subscribe to the event.
Upvotes: 0