Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type parameters using out

Im trying to make a universal parser using generic type parameters, but i can't grasp the concept 100%

    private bool TryParse<T>(XElement element, string attributeName, out T value) where T : struct
    {
        if (element.Attribute(attributeName) != null && !string.IsNullOrEmpty(element.Attribute(attributeName).Value))
        {
            string valueString = element.Attribute(attributeName).Value;
            if (typeof(T) == typeof(int))
            {
                int valueInt;
                if (int.TryParse(valueString, out valueInt))
                {
                    value = valueInt;
                    return true;
                }
            }
            else if (typeof(T) == typeof(bool))
            {
                bool valueBool;
                if (bool.TryParse(valueString, out valueBool))
                {
                    value = valueBool;
                    return true;
                }
            }
            else
            {
                value = valueString;
                return true;
            }
        }

        return false;
    }

As you might guess, the code doesn't compile, since i can't convert int|bool|string to T (eg. value = valueInt). Thankful for feedback, it might not even be possible to way i'm doing it. Using .NET 3.5

like image 400
Mikael Gidmark Avatar asked Apr 29 '10 13:04

Mikael Gidmark


1 Answers

The XElement and XAttribute classes both provide a set of explicit conversion operators (casts) to conveniently convert their contents to .NET primitive types.

For example, you can simply do:

XElement elem = // ...

string value1 = (string)elem.Attribute("myString");
int    value2 = (int)elem.Attribute("myInt");
int?   value3 = (int?)elem.Attribute("myOptionalInt");
bool   value4 = (bool)elem.Attribute("myBool");
like image 113
dtb Avatar answered Oct 15 '22 22:10

dtb