onConversationUpdated(); action no null check

I’m not sure where to ask this but this video’s as good as any, since it’s also happening here. Usually with actions, they’re wrapped in a null check, but this one isn’t. How come? I would expect:

if(onConversationUpdated != null)
{
onConversationUpdated();
}

I would prefer if we didn’t have to do a null check every time, honestly, but this was surprising

This was blind faith on Sam’s part, based on the assumption that OnConversation would not ever be null in the first place. While this works out in this case, I tend to distrust any assumptions. As a rule of thumb if you always null check events, you’ll never fire a null event.

Here’s a quick shortcut to make null checking easier called null propagation. With events, rather than a formal construct

if(onConversationUpdated !=null)
{
    onConversationUpdated();
}

You can put this all on one easy line:

onConversationUpdated?.Invoke();

image

The shortcut was a godsent. It’s so easy for it to become a habit, too. Eventually you don’t even think about it, you just write it like that. I don’t call any delegate without ?.Invoke() anymore

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms