0

I have just started learning C#. I'm making a game mod for Rimworld and cannot modify the pawn code. Apparently, any of the chained objects may be null. Is there a better way to bail out of the method than what I've done?

Thank you.

    private void cleanseParadoxicalMemories(Pawn pawn, Dictionary<string, string> knownPawnIDs)
    {
        if (pawn.needs == null || pawn.needs.mood == null || pawn.needs.mood.thoughts == null || pawn.needs.mood.thoughts.memories == null)
        {
            return;
        }

        // Remove any crazy-making memories from a now-invalid timeline due to traveling across an Einstein-Rosen bridge
        // (basically, selective amnesia about everyone not going with us.)
        foreach (var paradox in pawn.needs.mood.thoughts.memories.Memories.ToList())
        {
            if (paradox.otherPawn != null)
            {
                pawn.needs.mood.thoughts.memories.RemoveMemory(paradox);
            }
        }
    }
Theodore R. Smith
  • 21,848
  • 12
  • 65
  • 91
  • 2
    I think you could just use `?.` here, at least in the if. `pawn.needs?.mood?.thoughts?.memories` will be null if any of those are. If I’m not entirely mistaken `foreach` doesn’t like nulls so cant put the whole thing inside it – Sami Kuhmonen Aug 09 '20 at 15:48
  • Or `foreach(var paradox in (pawn?.needs?.mood?.thoughts?.memories?.Memories ?? Enumerable.Empty()).ToList())` – pinkfloydx33 Aug 09 '20 at 17:12

1 Answers1

3

You can use null conditional operator ?. to achieve this :

private void cleanseParadoxicalMemories(Pawn pawn, Dictionary<string, string> knownPawnIDs)
{
   if (pawn?.needs?.mood?.thoughts?.memories == null)
   {
      return;
   }

   // Remove any crazy-making memories from a now-invalid timeline due to traveling across an Einstein-Rosen bridge
   // (basically, selective amnesia about everyone not going with us.)
   foreach (var paradox in pawn.needs.mood.thoughts.memories.Memories.ToList())
   {
      if (paradox.otherPawn != null)
      {
         pawn.needs.mood.thoughts.memories.RemoveMemory(paradox);
      }
   }
Jasmeet
  • 1,315
  • 11
  • 23