score:2

Accepted 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).


Related Articles