简体   繁体   中英

Simplest way to check for DBNull and null at once

I'm querying a SQL Server database through C# to return a number from a specific row of a table.

The function's supposed to return the number, otherwise it returns 0. The issue is that sometimes the DB value is null, and sometimes it returns nothing at all. I'm looking for the most concise way to check for both of these options at once.

The simplest I've gotten it is:

return (value != DBNull.Value && value != null) ? (int)value : 0;

This is as brief as I've gotten it, but is there a single command that checks for both?

Edit:

Here's my whole block of code (featuring the selected answer's code), for the sake of analysis:

protected int getProfile(string user_id)
{
    using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MySqlConnection"].ConnectionString))
    {
        using (SqlCommand command = new SqlCommand("SELECT type FROM tbl_consultant WHERE fk_user_id = @user_id"))
        {
            command.Parameters.AddWithValue("@user_id", user_id);
            command.Connection = conn;

            conn.Open();
            var value = command.ExecuteScalar();

            return value as int? ?? 0;
        }
    }
}

You can use the ?? operator with nullables.

return (value as int?) ?? 0;

If you're feeling bold, you can even take out the parens.

You can make it an extension method

public static bool IsNotNull(this object value)
{
    return value != DBNull.Value && value != null;
}

return value.IsNotNull() ? (int)value : 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM