How to handle a null dictionary value?

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
thinklingsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AndyAinscowFreelance programmer / ConsultantCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
thinklingsAuthor 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 ArchitectCommented:
Hi Thinklings,
is the type of fieldvalues a ListDictionary?
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

thinklingsAuthor Commented:
It is ... Dictionary<string, string>
AndyAinscowFreelance programmer / ConsultantCommented:
>>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?
thinklingsAuthor 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 / ConsultantCommented:
ps.  Please post the code you used to test explicitly for a null value
Karrtik IyerSoftware ArchitectCommented:
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

thinklingsAuthor Commented:
I didn't use code. Just break points and checking the value of the variable at that given point.
AndyAinscowFreelance programmer / ConsultantCommented:
>>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 ArchitectCommented:
Hi Thinklings,
When you have sometime please try the code that I gave in my last comment.
Grant SpiteriSenior consultantCommented:
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 SotoRetiredCommented:
What happens if you do this:

if ((val.Value != String.Empty) && (val.Value.Contains(("signer" + sig.Value).ToString())))
kaufmed   ( ⚆ _ ⚆ )I asked the operating system what I could do to become a better programmer. It said, "Let me give you some pointers."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 / ConsultantCommented:
@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.
it_saigeDeveloperCommented:
*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-
kaufmed   ( ⚆ _ ⚆ )I asked the operating system what I could do to become a better programmer. It said, "Let me give you some pointers."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 / ConsultantCommented:
@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.
kaufmed   ( ⚆ _ ⚆ )I asked the operating system what I could do to become a better programmer. It said, "Let me give you some pointers."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 / ConsultantCommented:
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.
kaufmed   ( ⚆ _ ⚆ )I asked the operating system what I could do to become a better programmer. It said, "Let me give you some pointers."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?
thinklingsAuthor 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

thinklingsAuthor 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!!
thinklingsAuthor Commented:
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!
thinklingsAuthor 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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.