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);
}
}
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.
Don't check for it.
If you get nulls, you've added the handler to something you shouldn't have. And if some other bug causes it, you should be handling it with WinForms' global exception handler so the program doesn't bomb, logging it, and uploading the logs to your site whichever way you can to check for such errors.
Resharper likes option 1 as it is a pre-condition checker. When pre-conditions are not met, an early return is done.
Usually an early return is destructive for code-readability, but in this case it is very readable.
This way you can easily add extra pre-condition checks, like checking the contents of the EventArgs e, without having to rework the main function code.
Similar to @Konrad but I like the idea of adding the exception in the end if the code
So I vote for Option #2
I do not handle null for private methods, as I always make sure no null value will be sent to my private methods. If something went wrong and null has been passed to private method, so the exception will be thrown from as it should be and I will know that I did something wrong. If you always check for null value for private method, you might be skipping some logical error at run-time and you will never know you got one in your code until it hits you in the production.
you can use DBNull Class while assigning the value to an object...