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);
}
}
The best code is to disallow null
(instead of what you’re doing). This isn’t always possible (sometimes it’s important to handle null
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:
if (arg == null)
throw new ArgumentNullException("arg");
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 be null
and I’d say that a check for it is redundant. If null
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.
Why not just pretend that a null reference never occurs, and don't catch the NullPointerException?
You get a stack trace, plenty of information, and it's handled as an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With