Cannot assign null to anonymous property of type array

You have to use a typed null:

(List<Plane>)null

Or

(Plane[])null

Otherwise the compiler has no idea what type you want the anonymous type’s member to be.

Update
As @AakashM has rightly pointed out – this solves your problem of assigning a null to an anonymous member – but doesn’t actually compile – and if it did it wouldn’t allow you to refer to these members.

A fix would be to do this (unfortunately both the null and the anonymous Planes array will need casting:

var expected = new[] {
  new { 
          PilotName = "Higgins", 
          Planes = (IEnumerable)null
      },
  new {
          PilotName = "Higgins", 
          Planes = (IEnumerable)new [] {
                              new { PlaneName = "B-52" },
                              new { PlaneName = "F-14" } 
                          }
      }
};

So use IEnumerable as the member type. You could also use IEnumerable<object> but the effect will be the same either way.

Or – you could use IEnumerable<dynamic> as the common type – this would let you do this:

Assert.AreEqual("B-52", expected[1].Planes.First().PlaneName);

Leave a Comment