Generic conversion function doesn't seem to work with Guids

mattruma picture mattruma · Dec 26, 2008 · Viewed 12.2k times · Source

I have the following code:

public static T ParameterFetchValue<T>(string parameterKey)
{
    Parameter result = null;

    result = ParameterRepository.FetchParameter(parameterKey);

    return (T)Convert.ChangeType(result.CurrentValue, typeof(T), CultureInfo.InvariantCulture);  
}

The type of result.CurrentValue is string. I would like to be able to convert it to Guid but I keep getting the error:

Invalid cast from System.String to System.Guid

This works perfectly with primitive data types.
Is there any way to make this work for non-primitive data types?

Answer

Marc Gravell picture Marc Gravell · Dec 26, 2008

How about:

T t = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text);

Works fine for Guid and most other types.