Reputation: 522
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?
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;
}
}
}
Upvotes: 2
Views: 5898
Reputation: 101731
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;
Upvotes: 3
Reputation: 86154
You can use the ??
operator with nullables.
return (value as int?) ?? 0;
If you're feeling bold, you can even take out the parens.
Upvotes: 3