Generic type parameters using out

Posted by Mikael on Stack Overflow See other posts from Stack Overflow or by Mikael
Published on 2010-04-29T13:47:21Z Indexed on 2010/04/29 13:57 UTC
Read the original article Hit count: 422

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about polymorphism