Search code examples
c#.net.net-coresystem.reflectionactivator

Cannot convert type 'System.Reflection.PropertyInfo' to 'bool'


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;
        }
    }
}

Solution

  • 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);
            }
        }
    }