Iron
Iron

Reputation: 477

Generic Cast xAttribute to bool

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

Upvotes: 3

Views: 1365

Answers (1)

Iron
Iron

Reputation: 477

I just used the XmLConvert. Is an easy workaround. It even works with 0 and 1

Regards

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

        if(typeof(T) == typeof(bool))
        {
            object value = XmlConvert.ToBoolean(xAttribute.Value);
            output = (T) value;

            return true;
        }

        output = (T)Convert.ChangeType(xAttribute.Value, typeof(T));
        return true;
    }

Upvotes: 4

Related Questions