i'm using this extension method for converting objects in my project. But its unable to convert GUID
as its doesn't implements IConvertible
Interface but for conversion i always have to use new Guid(fooobject)
but i want that i could use this method to convert objects to GUID
. any idea how can we make it flexible to work with GUID
also.
Extension method is
public static T ToType<T>(this object val, T alt) where T : struct, IConvertible
{
try
{
return (T)Convert.ChangeType(val, typeof(T));
}
catch
{
return alt;
}
}
Because you have the constraint that the type you are converting to implements the
IConvertible
interface (whereas theGuid
structure) does not, you have no choice to create an overload, like this:When you pass a
Guid
, it will resolve because of section 7.4.2 of the C# specification (emphasis mine):Given that
Guid
is a more specific match than the type parameterT
, your second method will be called.Note, if you removed the
IConvertible
interface constraint, you could handle this in a single method, but you'd have to be able to have logic to handle any structure that is passed forT
(aTypeConverter
instance would be handy here).