2

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;
        }
    }
}
Community
  • 1
  • 1
MikeOShay
  • 522
  • 1
  • 7
  • 17
  • 1
    Where do you get `value` from? How does "nothing at all" end up as a null reference? – Guffa Oct 22 '14 at 18:59
  • Added example code to the post. Checks if a user has a profile, and what type of profile it is. If the profile type isn't set, it returns 0. For what I'm working with, restructuring the table to not allow nulls and just have 0 as the default is more trouble than it's worth. – MikeOShay Oct 22 '14 at 19:38

2 Answers2

3

You can use the ?? operator with nullables.

return (value as int?) ?? 0;

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

recursive
  • 83,943
  • 34
  • 151
  • 241
  • that is not gonna compile if the return type is int. – Selman Genç Oct 22 '14 at 19:03
  • 1
    Actually it did. It checks it as nullable int type (int? with the question mark), but if the "as int?" returns null, it returns a 0. Very concise answer, I never even knew about using "as" like that until now, and I've been trying to learn how to use "??" anyway, so this is a good jumping-on point. – MikeOShay Oct 22 '14 at 19:08
  • Though I think I should note that I'm going to keep the brackets in there, for sake of readability. If I have "? ??" smack-dab in my code there, then that'll be exactly the response of my coworkers, heh. – MikeOShay Oct 22 '14 at 19:19
3

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;
Selman Genç
  • 100,147
  • 13
  • 119
  • 184