Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle a NULL

Tags:

c#

null

resharper

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);
            }
        }
like image 827
NTBuddy Avatar asked Sep 28 '10 13:09

NTBuddy


2 Answers

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.

like image 154
Konrad Rudolph Avatar answered Oct 08 '22 14:10

Konrad Rudolph


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.

like image 35
Arafangion Avatar answered Oct 08 '22 12:10

Arafangion