Search code examples
c#linqenums

C# LINQ to XML: "Safe" enum value from an XElement?


To get a "safe" integer value from an XElement in C# one can use a method like

    public int GetIntegerValue(XElement x, string tag)
    {
        int result  = Int32.MinValue;
        if (x.Element(tag) != null)
        {
            Int32.TryParse(x.Element(tag).Value, out result);
        }
        return result;
    }

The code returns the correct integer value if the element is present and contains a parseable string, otherwise Int32.MinValue. This approach would function with a few other common types like double, bool, etc., but what about enum?

Can there also be a function like GetEnumValue(XElement x, string tag, Type enumType) or GetEnumValue(XElement x, string tag, TEnum defaultValue) or alike?


Solution

  • You can try following method:

    public static TEnum GetEnumValue<TEnum>(XElement x, string tag)
        where TEnum : struct
    {
        // Set default value
        TEnum parsedEnum = default(TEnum);
    
        var element = x.Element(tag);
        if(element != null)
        {
            // Try to parse
            Enum.TryParse<TEnum>(element.Value, out parsedEnum);
        }
    
        return parsedEnum;
    }
    

    And then call it like:

    CarType carType = GetEnumValue<CarType>(xElement, tag);