Extension method: how to make it work with GUID

I use this extension method to convert objects to my project. But it is not possible to convert it to a GUID , since it does not implement the IConvertible interface, but for conversion I should always use new Guid(fooobject) , but I want me to be able to use this method to convert objects to a GUID . any idea how we can make it flexible for working with GUID .

Extension method

  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; } } 
+4
source share
1 answer

Since you have a restriction that the type you are converting implements an IConvertible interface (whereas the Guid structure ), you have no choice to create an overload, for example:

 public static Guid ToType(this object val, Guid alt) { try { // Convert here. } catch { return alt; } } 

When you pass Guid , it will be resolved due to section 7.4.2 of the C # specification (my attention):

Once the candidate function members and the argument list have been identified, selecting the best member of the function in all cases:

  • Given the set of applicable candidate candidate members, the best member of the function in this set is found.

Given that Guid is a more specific match than a parameter of type T , the second method is called.

Please note that if you removed the IConvertible interface IConvertible , you could handle it in one method, but you would need to have logic to handle any structure that is passed to T (a TypeConverter would be convenient here).

+2
source

All Articles