Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

c#: how to convert string to custom template type (i.e. implement "T convertTo<T>(string)")

I want a function that can convert "string" to a given type T. I.e. I want to implement such function:

T convertTo<T>(string stringToConvert)

T could be actually either simple type or enum, but i don't know how to check actual T type at runtime. I.e. I can't write something like that:

if (T instanceof MyEnum) { return MyEnum.Parse(stringToConvert); }

How can I implement my function then?

Upvotes: 0

Views: 743

Answers (3)

Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

finally I've implemented function this way:

private static T ConvertFromString<T>(string text)
    {
        if (typeof(Enum).IsAssignableFrom(typeof(T)))
        {
            try
            {
                return (T)Enum.Parse(typeof(T), text);
            }
            catch (ArgumentException e)
            {
                return default(T);
            }
        }
        return (T)Convert.ChangeType(text, typeof(T));
    }

Upvotes: 0

Femaref
Femaref

Reputation: 61437

return (T)Enum.Parse(typeof(T), stringToConvert);

Upvotes: 1

Bob G
Bob G

Reputation: 1246

if (typeof(T) == typeof(MyEnum))
    return (T)Enum.Parse(typeof(T), stringToConvert);

Upvotes: 1

Related Questions