Trinitrotoluene
Trinitrotoluene

Reputation: 1458

Dealing with nulls in as little code as possible

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?

Upvotes: 1

Views: 94

Answers (1)

Grant Winney
Grant Winney

Reputation: 66439

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"];
}

Upvotes: 6

Related Questions