I have two Lists that are being populated via JSON deserialization
List<MyType> a = JsonConvert.DeserializeObject<List<MyType>>(jsonstringa);
List<MyType> b = JsonConvert.DeserializeObject<List<MyType>>(jsonstringb);
I then iterate over each one and perform some some logic. It is entirely within reason that these collections may be empty.
foreach (MyType myA in a)
{
//DO STUFF HERE
}
foreach (MyType myB in b)
{
//DO STUFF HERE
}
When there are items in the collection for either, there are no problems. However, when there are no items in List B, I get an "Object reference not set to an instance of an object" Exception thrown on the "foreach" line. This, however, does not occur with List A.
I took it a step further and changed the above code just to be safe as well, so that it looks like the following:
if (a.Count > 0)
{
foreach (MyType myA in a)
{
//DO STUFF HERE
}
}
if (b.Count > 0)
{
foreach (MyType myB in b)
{
//DO STUFF HERE
}
}
The iteration through the "A" list goes fine whether it's an empty collection or has elements. The iteration through the "B" list again goes fine if there are elements in the collection, but again throws the same exception except this time at the (myB.Count) > 0
line. Through debugging, the Count property for both collections reveal '0' when the collection is empty (as I would expect).
The custom "MyType" class has a default constructor with all non-virtual variables declared as such:
namespace MyApp.Models
{
public class MyType
{
public int ID { get; set; }
public string Code { get; set; }
public int ParentID { get; set; }
[ScriptIgnore(ApplyToOverrides = true)]
[JsonIgnore]
public virtual Parent Parent { get; set; }
public MyType()
{
ID = 0;
Code = null;
ParentID = 0;
}
}
}
I'm a bit at a loss. I have other custom types that are also failing here, but the fact that this pairing of identical types with one getting through just fine and the other throwing the exception is suspect to me and hopefully can help someone give me some insight as to this behavior.