I'm new to reflection, I want to know how to filter out the private properties and also get only the properties that are instantiated. Sample of what I would like to achieve is given below.
public class PersonalDetails
{
internal Address AddressDetails { get; set; }
public Contact ContactDetals { get; set; }
public List<PersonalDetails> Friends { get; set; }
public string FirstName { get; set; }
private int TempValue { get; set; }
private int Id { get; set; }
public PersonalDetails()
{
Id = 1;
TempValue = 5;
}
}
public class Address
{
public string MailingAddress { get; set; }
public string ResidentialAddress { get; set; }
}
public class Contact
{
public string CellNumber { get; set; }
public string OfficePhoneNumber { get; set; }
}
PersonalDetails pd = new PersonalDetails();
pd.FirstName = "First Name";
pd.ContactDetals = new Contact();
pd.ContactDetals.CellNumber = "666 666 666";
When I get the properties of object pd I want to filter out the properties that are private and not instantiated, like properties TempValue, Id and AddressDetails
Thanks in advance.
Maybe this
var p = new PersonalDetails();
var properties = p.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(x => x.GetValue(p) != null && !x.GetMethod.IsPrivate && !x.SetMethod.IsPrivate)
.ToList();
Additional Resources
Specifies flags that control binding and the way in which the search for members and types is conducted by reflection.
Returns the property value of a specified object.