Generic conversion function doesn't seem to work with Guids
-
23-08-2019 - |
Question
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?
Solution
How about:
T t = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text);
Works fine for Guid
and most other types.
OTHER TIPS
Try This:
public object ChangeType(object value, Type type)
{
if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
if (value == null) return null;
if (type == value.GetType()) return value;
if (type.IsEnum)
{
if (value is string)
return Enum.Parse(type, value as string);
else
return Enum.ToObject(type, value);
}
if (!type.IsInterface && type.IsGenericType)
{
Type innerType = type.GetGenericArguments()[0];
object innerValue = ChangeType(value, innerType);
return Activator.CreateInstance(type, new object[] { innerValue });
}
if (value is string && type == typeof(Guid)) return new Guid(value as string);
if (value is string && type == typeof(Version)) return new Version(value as string);
if (!(value is IConvertible)) return value;
return Convert.ChangeType(value, type);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow