I have a class, called Permissions, it has a few subclasses (and some properties), Group and Group.Permission.
Now, I CAN do the following
Permissions u = new Permissions();
u.userId = (Guid)user.ProviderUserKey;
List<int> groups = getGroupsForUserId(u.userId.ToString());
List<Permissions.Group> groupItems = new List<Permissions.Group>();
foreach (int g in groups)
{
Permissions.Group groupItem = new Permissions.Group();
groupItem.group_id = g;
groupItem.Records = getRecordsForGroupId(g);
groupItem.Permissions = getPermissionsForGroupId(g);
groupItems.Add(groupItem);
}
u.Groups = groupItems;
However, I CAN’T do this:
Permissions u = new Permissions();
u.userId = (Guid)user.ProviderUserKey;
List<int> groups = getGroupsForUserId(u.userId.ToString());
foreach (int g in groups)
{
Permissions.Group groupItem = new Permissions.Group();
groupItem.group_id = g;
groupItem.Records = getRecordsForGroupId(g);
groupItem.Permissions = getPermissionsForGroupId(g);
u.Groups.Add(groupItem);
}
My question, why?
I created a new Permissions.Group object, added the values and then added it to the u object’s list of Groups. To my mind that should work, however I assume I’ve not wired something up in my class? My class just is a list of properties property_name { get; set; } so isn’t anything exotic really.
Trying the latter, I get a NullReferenceException on the line u.Groups.Add(groupItem);
You probably need to initialize
Permissions.Groupsin yourPermissionsconstructor: