Search code examples
c#.netenumsattributesiconvertible

How compiler select method between 2 with similar signature?


I have Enum

public enum ContentMIMEType
{
    [StringValue("application/vnd.ms-excel")]
    Xls,

    [StringValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")]
    Xlsx
}

In extensions I have 2 methods to get attribute value:

public static string GetStringValue<TFrom>(this TFrom enumValue) 
            where TFrom : struct, IConvertible
{
    ...
}

and

public static string GetStringValue(this Enum @enum)
{
    ...
}

These methods have different signature, but when I execute next operation ContentMIMEType.Xlsx.GetStringValue() 1st method is taken.

Why this happens, cause execution of 2nd method for me is more obvious (have tried to change sort order, but doens't help).


Solution

  • Here is more.

    Simply from site:

    overloading is what happens when you have two methods with the same name but different signatures. At compile time, the compiler works out which one it's going to call, based on the compile time types of the arguments and the target of the method call.

    And when compiller cannot deduct which is proper, compiller return error.

    EDIT:

    Based on Constraints on type parameters and Enum Class enum is struct and implement IConvertible so meets requirements and compiler use first matched. No conflict with Enum because Enum is lover than struct in inheritance hierarchy.