Reputation: 482
I am initializing a class at runtime using Activator.CreateInstance. How do I loop through all the properties of the class that is initialized? I get a compile-time error 'Cannot convert type 'System.Reflection.PropertyInfo' to 'bool''
public class CustomOperations<T> where T : class
{
public void AssignValues(int input)
{
T newObject = default(T);
newObject = Activator.CreateInstance<T>();
foreach (PropertyInfo prop in newObject.GetType().GetProperties().ToList())
{
//Getting a compile time error - Cannot convert type 'System.Reflection.PropertyInfo' to 'bool'
bool field = (bool)prop;
}
}
}
Upvotes: 0
Views: 179
Reputation: 1632
prop
is of type PropertyInfo
if you want the actual value of newobject
you need to get the value of it.
I changed the code below(And added a security so it only gets propeties of type bool
)
public class CustomOperations<T> where T : class
{
public void AssignValues(int input)
{
T newObject = default(T);
newObject = Activator.CreateInstance<T>();
foreach (PropertyInfo prop in newObject.GetType().GetProperties().Where(p=>p.PropertyType == typeof(bool)).ToList())
{
bool field = (bool)prop.GetValue(newObject);
}
}
}
Upvotes: 1