How to handle a null dictionary value?

thinklings
thinklings used Ask the Experts™
on
Hi,

I have the following code that manipulates a dictionaries value. The dictionary list is fieldValues. The purpose is that I check if the value contains a certain string and if it does, I replace it with the value of another dictionary value.


foreach (var val in fieldValues)
{                    
          if (val.Value.Contains(("signer" + sig.Value).ToString()))
          {
                    fieldValues[val.Key] = val.Value.Replace((sig.Value).ToString(), (sig.Key).ToString());
          }                                        
}

Open in new window


Although this shouldn't happen, sometimes the dictionary value is null and the program crashes. I just want to know how I should handle the null dictionary values so that the foreach lp
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Freelance programmer / Consultant
Commented:
Do you mean changing
if (val.Value.Contains(("signer" + sig.Value).ToString()))
to something like
if ((val.value != null) && (val.Value.Contains(("signer" + sig.Value).ToString())))

ie.  Check if it is null value and only process the next lines if it is not null

Author

Commented:
Hi Andy,

Thanks for your suggestion although I already tried this and it still crashes at that point when it queries against a null dictionary value...
Karrtik IyerSoftware Architect

Commented:
Hi Thinklings,
is the type of fieldvalues a ListDictionary?
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Author

Commented:
It is ... Dictionary<string, string>
AndyAinscowFreelance programmer / Consultant

Commented:
>>it still crashes at that point when it queries against a null dictionary value...

Is that a guess or have you checked?  Also how did you check?

Author

Commented:
I checked by going through the code using breakpoints.. When it reaches the if statement and the value of cal.Value is null, it exits the loop. I do not get a specific error. It just stops processing any code from that point on.
AndyAinscowFreelance programmer / Consultant

Commented:
ps.  Please post the code you used to test explicitly for a null value
Karrtik IyerSoftware Architect
Commented:
Can you please trygetvalue of dictionary, I have modified your code below, can you please try with it?
            foreach (var val in fieldValues)
            {
                string strval = string.Empty;
                fieldValues.TryGetValue(val.Key, out strval);
                if (strval != string.Empty && strval.Length > 0)
                {
                    if (strval.Contains(("signer" + sig.Value).ToString()))
                    {
                        fieldValues[val.Key] = val.Value.Replace((sig.Value).ToString(), (sig.Key).ToString());
                    }       
                }
            }

Open in new window

Author

Commented:
I didn't use code. Just break points and checking the value of the variable at that given point.
AndyAinscowFreelance programmer / Consultant

Commented:
>>I didn't use code.

I think you misunderstood me.
Please post the code you used instead of my suggestion:
if ((val.Value != null) && (val.Value.Contains(("signer" + sig.Value).ToString())))

If val.Value is null then the 'contains' is not run as the if statement is false - no crash should be possible with a null value in val.
Karrtik IyerSoftware Architect

Commented:
Hi Thinklings,
When you have sometime please try the code that I gave in my last comment.
Grant SpiteriSenior consultant
Commented:
if(fieldValues==null || fieldValues.Count ==0)
    //Handle it accordingly

foreach (var val in fieldValues)
{        
     if(val == null || val.Value ==null || sig==null || sig.Value == null || sig.Key)
         continue;
          if (val.Value.Contains(("signer" + sig.Value)))
                    fieldValues[val.Key] = val.Value.Replace((sig.Value).ToString(), (sig.Key).ToString());                          
}
Fernando SotoRetired
Distinguished Expert 2017
Commented:
What happens if you do this:

if ((val.Value != String.Empty) && (val.Value.Contains(("signer" + sig.Value).ToString())))
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
* No Points *

Not too fond of his formatting, but Grant Spiteri has the right idea:  check for null prior to trying to use the value. You can do this within the if as he demonstrates.
AndyAinscowFreelance programmer / Consultant

Commented:
@kaufmed
http://www.experts-exchange.com/questions/28896502/How-to-handle-a-null-dictionary-value.html#a41360821

According to the asker it is not 'val' but the value it contains 'val.Value' that can be null.
I'm still waiting for the code to be posted that was actually used when I suggested checking for a null explicitly and only continuing if it was not null - see the first comment to the question.

Commented:
*No Points*

I am in agreenment with Kaufmed, you just need to check that val.Value is not null; e.g. -
foreach (var val in fieldValues)
{
	if (val.Value != null && val.Value.Contains(("signer" + sig.Value).ToString()))
	{
		fieldValues[val.Key] = val.Value.Replace((sig.Value).ToString(), (sig.Key).ToString());
	}
}

Open in new window

You could add an additional check against sig as proposed by Grant (the check against val is unnecessary as these are KeyValuePair objects, the Value property is defined so the Value object can be null but not Value itself); e.g. -
foreach (var val in fieldValues)
{
	if (val.Value != null && sig != null && sig.Value != null && val.Value.Contains(("signer" + sig.Value).ToString()))
	{
		fieldValues[val.Key] = val.Value.Replace((sig.Value).ToString(), (sig.Key).ToString());
	}
}

Open in new window


-saige-
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
@Andy

Grant Spiteri's suggestion covers both situations, though I'm not sure what the latter part of the if is doing.
AndyAinscowFreelance programmer / Consultant

Commented:
@kaufmed
Agreed, but the asker does actually specifically talk about val.Value being null.  If val is null then how can one actually check what the contents are - my visual studio doesn't allow that at a breakpoint, it just says val is null.  ergo:- val is not null.

I did actually write this in the first comment:
ie.  Check if it is null value and only process the next lines if it is not null

I've also asked a couple of times for the code actually used when the checking for null is being performed.
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
I may be missing something in what you're saying, but "short-circuiting" in C# will prevent the second condition, val.Value ==null, (and all remaining conditions) from being checked if the first condition, val == null, is true.
AndyAinscowFreelance programmer / Consultant

Commented:
I'm not talking of the C# code.  I understand the 'short circuit' which is why the construct in my first comment is safe, it will exit if the val.value is null before attempting to check if the string is contained with the val.value part (no crash).  

I'm talking about how does one see val.Value is null.  When a breakpoint is hit one can inspect the contents of a variable.  If val is null then there are no contents - one can't inspect the contents in the IDE.  So for val.Value to be null at a breakpoint it means val is not null.  The asker does say val.Value is null in his case.
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
If val is null then there are no contents - one can't inspect the contents in the IDE.  So for val.Value to be null at a breakpoint it means val is not null.
Agreed. So what is the issue?

Author

Commented:
Hi everyone,

Sorry for the delayed response.

Thank you for all your suggestions. Karrtik, unfortunately your code didn't work.

Andy, the code used was as suggested:

foreach (var val in fieldValues)
{
                    if ((val.Value != null) && (val.Value != string.Empty) && (val.Value.Contains(("signer" + sig.Value).ToString())))
                    {
                        fieldValues[val.Key] = val.Value.Replace((sig.Value).ToString(), (sig.Key).ToString());
                    }                                                                 
}

Open in new window

Author

Commented:
I just tested the loop on it's on and without the following code in it and it seemed to be working fine...

fieldValues[val.Key] = val.Value.Replace((sig.Key).ToString(), (sig.Value).ToString());

Open in new window


It seems that somehow the above line of code disrupts the foreach loop. Not sure why..

Sorry about the confusion!!
I just discovered this article -

http://www.c-sharpcorner.com/Blogs/10905/updating-dictionary-elements-while-iterating.aspx

Apparently Dictionaries are read only when in foreach loops, hence the code breaking.

Thanks for all your help anyway!

Author

Commented:
The initial thought of why the issue was occurring did not end up the being the cause. The experts solutions would have been correct if that was the cause.

The solution I have provided is the true solution for the actual issue.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial