Reputation: 3531
I'm writing a Winforms Control, that wraps a JS library and extends a web browser control.
When the JS library, calls an event, I have a callback to a method in C# that parses the returned JSON etc... At the end of that method, I want to fire an event, with the data returned from JS.
I'm doing the following:
public event EventHandler<WebMercatorCoordinates> OnMapClick;
public void JavascriptCallbackReceiver(String message)
{
//I'm parsing the string here
if (OnMapClick != null)
this.OnMapClick(this, new WebMercatorCoordinates(lat, lng));
}
I do not like that null check. I have to check for it, so as to not call a null delegate, if the user has not added his own handler to EventHandler<WebMercatorCoordinates> OnMapClick
.
Should I, in the constructor of the class, add a handler to the event so that it is never null (the object will catch its own event)? I don't like that either (sounds way worse).
Is there some better way to design/wirte this?
Upvotes: 1
Views: 60
Reputation: 3212
Using the C# 6 null-conditional operator you can write:
OnMapClick?.Invoke(this, new WebMercatorCoordinates(lat, lng));
Upvotes: 2