Here is my code, which works perfectly except for one case: when I have an xAttribute of bool, so xAttribute.Value == 1. In this situation, Convert doesn’t work for a numeric type.
Normally I would just use output = (bool) xAttribute, which works; but in this method I have a generic type, so I want to use that generic type along the lines of output = (T) xAttribute. How can I do this?
public static bool TryGetValueFromAttribute<T>(
this XElement element,
String attName,
out T output,
T defaultValue)
{
var xAttribute = element.Attribute(attName);
if (xAttribute == null)
{
output = defaultValue;
return false;
}
output = (T)Convert.ChangeType(xAttribute.Value, typeof(T));
return true;
}
I just used the XmLConvert. Is an easy workaround. It even works with 0 and 1
Regards