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 prefer
with it there are less nested operations in code and early exit if there is null.
I generally go with Option #1. I feel it's cleaner and it's meaning is more clear. Whoever's reading the code knows that if we've safely gotten past the null check and have exited then there's no chance of us messing around with a null value in sender later on.
The best code is to disallow
null
(instead of what you’re doing). This isn’t always possible (sometimes it’s important to handlenull
in a meaningful way) – but in most of the cases it is.Then all you need to do (in defensive coding) is to add a
null
check and throw an exception:Many (if not most) methods in the .NET framework and in good libraries do it that way.
Apart from that, the
sender
of an event should never benull
and I’d say that a check for it is redundant. Ifnull
gets passed to this event, there’s something seriously wrong with your code.The way you handle
null
(by silently swallowing it and doing nothing) may mask serious bugs in the application and is rarely, if ever, appropriate. Errors in the code should raise suspicious behaviour, not be swept under the carpet.If you're not going to handle a null sender, then I would go with the first option (and make sure it's the first line in the handler so it doesn't get hidden by other code).
If you think you may handle a null sender eventually, I would go with the second option since it offers you a better way to handle things as well as maintaining a single return point for the handler.
Option 1 is being suggested by resharper, in my opinion, because it makes for easier to read code. You'll end up with:
As far as performance is concerned, there's probably little difference (though if it matters to you, measure it). There's nothing to stop the JIT compiler from re-writing one form to the other anyway, if they don't get output as identical MSIL by the C# compiler anyway.
Option #1 I guess would reduce Cyclomatic complexity. In option #2 , if there is another if conditions then it would come under the if clause and increase the complexity