I’m attempting to dump variable property information to a simple string but when it gets to my nullable bools, the as string always returns null –even if the actual value is true | false!
StringBuilder propertyDump = new StringBuilder();
foreach(PropertyInfo property in typeof(MyClass).GetProperties())
{
propertyDump.Append(property.Name)
.Append(":")
.Append(property.GetValue(myClassInstance, null) as string);
}
return propertyDump.ToString();
No exceptions are thrown; quick and the output is exactly what I want except any properties that are bool? are always false. If I quick watch and do .ToString() it works! But I can’t guarantee other properties are not, in fact, null.
Can anyone explain why this is? and even better, a workaround?
The
asoperator returns a casted value if the instance is of that exact type, ornullotherwise.Instead, you just should
.Append(property.GetValue(...));Append()will automatically handle nulls and conversions.