How compiler select method between 2 with similar signature?

48 views Asked by At

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

2

There are 2 answers

1
BWA On BEST ANSWER

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.

0
Jon Hanna On

The signature:

public static string GetStringValue<TFrom>(this TFrom enumValue) 

Is a generic signature, which means that it is allowed to be treated as:

public static string GetStringValue<ContentMIMEType>(this ContentMIMEType enumValue) 

Which is more specific than:

public static string GetStringValue(this Enum @enum)

And is therefore the method chosen.