HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Check for null/empty in dictionary

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nullemptyfordictionarycheck

Problem

I am doing the following about 10 times with other strings, so the code is duplicated. How can I refactor this?

queryWhere is a Dictionary that contains parameters that will be passed to a query.

string account = string.Empty;

if (queryWhere.ContainsKey("account") 
&& queryWhere["account"] != null 
&& !string.IsNullOrEmpty(queryWhere["account"].ToString()))
    account = queryWhere["account"].ToString();

string customer = string.Empty;

if (queryWhere.ContainsKey("customer ") 
&& queryWhere["customer "] != null 
&& !string.IsNullOrEmpty(queryWhere["customer "].ToString()))
    customer = queryWhere["customer "].ToString();

string balance = string.Empty;

if (queryWhere.ContainsKey("balance ") 
&& queryWhere["balance "] != null 
&& !string.IsNullOrEmpty(queryWhere["balance "].ToString()))
    balance = queryWhere["balance"].ToString();

Solution

Each of these:

string account = string.Empty;

if (queryWhere.ContainsKey("account") 
   && queryWhere["account"] != null 
   && !string.IsNullOrEmpty(queryWhere["account"].ToString()))
{
    account = queryWhere["account"].ToString();
}


Should be reduced to:

string account;
if(!queryWhere.TryGetValue("account", out account))
{
   account = string.Empty; // if you need the string to be empty // default is null
}


Dictionary.TryGetValue

But that logic can then be moved to a method:

private string GetValue(string key)
{
   string returnValue;
   if(!queryWhere.TryGetValue(key, out returnValue))
   {
      returnValue= string.Empty;
   }
   return returnValue;
}

string account = GetValue("account");
string customer = GetValue("customer");


I really don't see the point of your original code, BTW. For instance, the .ToString() is completely superfluous, since you're working with a Dictionary. It is always going to return a string.

But why do you even check for string.IsNullOrEmpty()? You already know it isn't null from the previous line's check -- queryWhere["account"] != null -- so at worst it is empty which is your default value anyway!

Code Snippets

string account = string.Empty;

if (queryWhere.ContainsKey("account") 
   && queryWhere["account"] != null 
   && !string.IsNullOrEmpty(queryWhere["account"].ToString()))
{
    account = queryWhere["account"].ToString();
}
string account;
if(!queryWhere.TryGetValue("account", out account))
{
   account = string.Empty; // if you need the string to be empty // default is null
}
private string GetValue(string key)
{
   string returnValue;
   if(!queryWhere.TryGetValue(key, out returnValue))
   {
      returnValue= string.Empty;
   }
   return returnValue;
}

string account = GetValue("account");
string customer = GetValue("customer");

Context

StackExchange Code Review Q#87202, answer score: 17

Revisions (0)

No revisions yet.