Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic conversion function doesn't seem to work with Guids

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?

like image 471
mattruma Avatar asked Dec 26 '08 12:12

mattruma


People also ask

How do I convert GUID?

Program to convert string into guid in . Net Framework using C# Guid. Parse method. This method contains two parameters string as an input and if this method returns true then result parameter contains a valid Guid and in case false is returned result parameter will contain Guid.

Which function converts a string value to generic number value?

The isNaN() function converts the given value to a number before checking it the given number is equal to NaN .


1 Answers

How about:

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

Works fine for Guid and most other types.

like image 126
Marc Gravell Avatar answered Sep 19 '22 14:09

Marc Gravell