I am having issues with the following code. I am iterating through a set to see if an object has a certain property type and if so, do some conversion to it.
var props = obj.GetType().GetProperties();
foreach (var p in props)
{
if (p.PropertyType == typeof(System.Boolean))
{
var conv = Convert.ToByte(p);
}
}
I get the following error when I try to run it:
"Unable to cast object of type 'System.Reflection.RuntimePropertyInfo' to type 'System.IConvertible'."
I assume you want to get the value of the property and convert that to a byte, right? Not the property itself... so:
var conv = Convert.ToByte(p.GetValue(obj, null));
It seems odd to have it as a byte
rather than a bool
, admittedly... I'd have expected:
var conv = (bool) p.GetValue(obj, null);
I'd also personally use:
if (p.PropertyType == typeof(bool))
rather than spelling out the System.Boolean
explicitly.
See more on this question at Stackoverflow