Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to check for null values?

People also ask

Which method can be used to check null?

In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.

Why is checking for null a good practice?

It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.

Should you always check for null?

In any case, it is always good practice to CHECK for nulls on ANY parameters passed in before you attempt to operate on them, so you don't get NullPointerExceptions when someone passes you bad data. Show activity on this post. If you don't know whether you should do it, the chances are, you don't need to do it.


What about

string y = (Session["key"] ?? "none").ToString();

If you're frequently doing this specifically with ToString() then you could write an extension method:

public static string NullPreservingToString(this object input)
{
    return input == null ? null : input.ToString();
}

...

string y = Session["key"].NullPreservingToString() ?? "none";

Or a method taking a default, of course:

public static string ToStringOrDefault(this object input, string defaultValue)
{
    return input == null ? defaultValue : input.ToString();
}

...

string y = Session["key"].ToStringOrDefault("none");

You could also use as, which yields null if the conversion fails:

Session["key"] as string ?? "none"

This would return "none" even if someone stuffed an int in Session["key"].


If it will always be a string, you can cast:

string y = (string)Session["key"] ?? "none";

This has the advantage of complaining instead of hiding the mistake if someone stuffs an int or something in Session["key"]. ;)


All of the suggested solutions are good, and answer the question; so this is just to extend on it slightly. Currently the majority of answers only deal with null validation and string types. You could extend the StateBag object to include a generic GetValueOrDefault method, similar to the answer posted by Jon Skeet.

A simple generic extension method that accepts a string as a key, and then type checks the session object. If the object is null or not the same type, the default is returned, otherwise the session value is returned strongly typed.

Something like this

/// <summary>
/// Gets a value from the current session, if the type is correct and present
/// </summary>
/// <param name="key">The session key</param>
/// <param name="defaultValue">The default value</param>
/// <returns>Returns a strongly typed session object, or default value</returns>
public static T GetValueOrDefault<T>(this HttpSessionState source, string key, T defaultValue)
{
    // check if the session object exists, and is of the correct type
    object value = source[key]
    if (value == null || !(value is T))
    {
        return defaultValue;
    }

    // return the session object
    return (T)value;
}