1

I'm relatively new to C# so please bear with me! The code I would prefer to write throws a null references if there is nothing in the dictionary, as it should. I'm having to cast it as string as the dictionary returns an object:

string mainDirectorsInZim = (string)zimOrganisation.OrganizationFields["main_director"];

The code I am having to write to solve that?

if (zimOrganisation.OrganizationFields.ContainsKey("main_director"))
  {
      mainDirectorsInZim = (string)zimOrganisation.OrganizationFields["main_director"];
  }
  else
  {
     mainDirectorsInZim = null;
  }

I have not an insignificant amount of these to write, and it seems inefficient. Is there a better way to do this?

Trinitrotoluene
  • 1,388
  • 5
  • 20
  • 39
  • 3
    which part of the first code throwing `NullReferenceException` ? it will only throw if the dictionary is null. Are you sure it doesn't throw `KeyNotFoundException`? – Selman Genç Jan 28 '16 at 21:41
  • 1
    See if this helps you: [Cleaner way to do a null check in C#?](http://stackoverflow.com/questions/17672481/cleaner-way-to-do-a-null-check-in-c) – Chris Stillwell Jan 28 '16 at 21:52

1 Answers1

6

I tried to reduce the code slightly by using the TryGetValue method, but as serhiyb pointed out in the comments, it wouldn't work due to having to convert the object to a string.

But this should be slightly more efficient still.

string mainDirectorsInZim = null;
object tmp;

if (zimOrganisation.OrganizationFields.TryGetValue("main_director", out tmp))
{
    mainDirectorsInZim = (string)tmp;
}

OTOH, you could just initialize your string to null to begin with, and eliminate the else block, if you happen to find that easier to understand since it's closer to your existing code.

string mainDirectorsInZim = null;

if (zimOrganisation.OrganizationFields.ContainsKey("main_director"))
{
    mainDirectorsInZim = (string)zimOrganisation.OrganizationFields["main_director"];
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • 1
    Great answer, but probably needs additional variable since second generic parameter is not string (object probably based on OP code). – serhiyb Jan 28 '16 at 21:44
  • 1
    But your approach is better since dictionary indexer is called only once. – serhiyb Jan 28 '16 at 21:50