public class Address { public string ZipCode {get; set;} } public class Customer { public Address Address {get; set;} }
how can I access eitther ‘ZipCode’ or ‘Address.ZipCode’ with reflection? For example:
Typeof(Customer).GetProperty('ZipCode')?
You’d need something like:
Basically if you want to take a string ‘Address.ZipCode’ and navigate down it, you need to split it by ‘.’ and then call GetProperty on the appropriate type at every step to get the property itself, then PropertyInfo.GetValue to get the next value in the chain. Something like this:
Call it like this:
Note that this works on the compile-time types of the properties. If you want it to cope with the execution time type (e.g. if customer.Address didn’t have a ZipCode property, but the actual type returned by Address did) then change
property.PropertyTypetoproperty.GetType().Also note that this doesn’t have any error handling etc 🙂