Okay here is the scenario! I have a Person object which has an Address object. Person has a list of Addresses.
Now, I want to iterate through the properties of the Person and when I reach a List I want to create an object of the Address object. How can i do that?
Update:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
private List<Address> _addresses = new List<Address>();
public void AddAddress(Address address)
{
_addresses.Add(address);
address.Person = this;
}
public List<Address> Addresses
{
get { return _addresses; }
set { _addresses = value; }
}
}
var properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach(var property in properties)
{
var propertyType = property.PropertyType;
if (!propertyType.IsGenericType) continue;
var obj = Activator.CreateInstance(propertyType);
var genericType = obj.GetType().GetGenericTypeDefinition();
Console.WriteLine(obj.GetType().Name);
var type = property.GetType();
}
The above reflection code returns me a List but it is of type List. I want the Generic Type which is address.
Tony, if you have access to Address class then you could simply do this.