At the top of my functions I'm trying the best way to handle a null coming into my procedures in C#. Which is the best way for checking and handling the null and why? I've added the complete code of what I'm using right now and Resharper is telling me to use Option #1. Normally I do what it says as I understand why it makes it more efficient. This time though I'm not sure so I must ask.
Option #1
if (sender == null) return;
// Code goes here
or
Option #2
if (sender != null)
{
// Code goes here
}
Complete Code
private void EmployeeMouseHoverToolTip(object sender, EventArgs e)
{
if (sender != null)
{
var sUserIdentifier = ((C1TextBox)sender).Text;
var userIdentifier = Guid.Empty;
if (Utilities.IsGuid(sUserIdentifier))
{
userIdentifier = new Guid(sUserIdentifier);
}
var toolTipText = Utilities.UserIdentifierToName(userIdentifier);
c1SuperTooltip.SetToolTip(sender as C1TextBox, toolTipText);
}
}
I personally prefer the first option
It cuts down on nesting and increases readability.
A variation of option #1 that either returns right away, or throws an exception. The trick is knowing which method to use. My rule of thumb is that if it's part of a public interface, then throw an exception. If it's something you have control over deep down in your framework then just return immediately and handle the null reference at that level.
In the specific case of your event handler:
Based on what ILDASM says, I would say option #2 is (slightly) more efficient:
Code:
ILDASM for Method1:
ILDASM for Method2:
The performance impact is minimal, so I wouldn't even worry about that. Option 1 is better because it is more readable and less cloudy...
More readable because the conditional is not negated, and there isn't an unnecessary scope block.
This is an event handler, it should only be called by controls in response to an event (never directly by your own code), so you shouldn't care about null checks or even type checks on the
sender
parameter (if you only attach this event handler to the same type of control). I'd do it simply like this:Actually, I'd go one step further and separate the logic to get the tooltip text from the logic to read and update the UI. Something like this:
Therefore, you shouldn't use any of the options you provided.
In your exact example here, go for the inverse of what you are doing, so if sender is null, go for an early exit. It reads better (IMO) and results in less nesting.
So Option #1 in this instance