Extension method : how to make it work with GUID also

2.1k views Asked by At

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;
        }
    }
1

There are 1 answers

0
casperOne On BEST ANSWER

Because you have the constraint that the type you are converting to implements the IConvertible interface (whereas the Guid structure) does not, you have no choice to create an overload, like this:

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

When you pass a Guid, it will resolve because of section 7.4.2 of the C# specification (emphasis mine):

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

  • Given the set of applicable candidate function members, the best function member in that set is located.

Given that Guid is a more specific match than the type parameter T, 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 for T (a TypeConverter instance would be handy here).