Reputation: 365
I have a 'Profile' object/class with an IList of 'Addresses', of which, I will only know their type [profile / addresses] at runtime via GetType() / GetProperties() etc., though I wish to .Add to this list e.g.:
var profile = session.Get<ProfileRecord>(1);
dynamic obj = new ExpandoObject();
obj = profile;
obj["Addresses"].Add(addressNew);
This does not work due to:
Cannot apply indexing with [] to an expression of type 'Test.Models.ProfileRecord'.
I've been looking at IDictionary, but have been unsuccessful in my attempts, nor even know if I should be heading down that path - so what is the correct way to go about this? This entire concept is new to me, so please don't over assume my capabilites ;) Many thanks in advance.
Upvotes: 0
Views: 54
Reputation: 891
You could do it like this if you dont know the type of profile.
var prop = profile.GetType().GetProperty("Addresses").GetValue(profile);
prop.GetType().GetMethod("Add").Invoke(prop, new object[] {1}); // Add the Value to the list
But then you must be sure the List is already initalized.
But i think you should be able to cast your object and set the Property directly like:
if(profile.GetType == typeof (ProfileRecord))
{
var record = (ProfileRecord)profile;
if (profile.Addresses == null)
{
profile.Addresses = new List<Address>();
}
prfile.Addresses.Add(addressNew);
}
Upvotes: 1