Wednesday, December 4, 2013

C# Events – Concepts and Caveats – Part 4

I hope you have gone through the Part 1 to 3 of C# events.
C# Events – NullReferenceException –
If you raise an event without handlers then you get this exception – Object reference not set to instance of an object. Look below screenshot. I have commented the registration of event from Fielder class and similarly for Fan class. Also commented null check from Ball class from event raising code –

 


 
The exception is reported because none of the objects have added their event handlers to an event BallInGround, hence it will be null. Therefore it is always necessary to check null condition before raising an event.