简体   繁体   中英

Why does the compiler pick the extension method on string over implicit char array?

If I have System.Linq imported, I can use this ToArray overload in the following call:

var x = "foo".ToArray();

and x is assigned a char[] with three elements that are the characters from the string "foo" . Then if I add a custom extension method in scope:

public static T[] ToArray<T>(this T toConvert) => new[] { toConvert };

The compiler silently changes its mind and x becomes a string[] with one element that is the string "foo" .

Why did the compiler not complain about ambiguity? I know some seemingly-ambiguous situations are resolved automatically by the compiler without errors, but I can't find any documentation or references about this type of situation. Basically, it seems that treating a string as a string rather than an implicit array of char seems to be the preferred behavior...

The first extension method you reference:

public static TSource[] ToArray<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);

Converts an IEnumerable<TSource> to an array (interface of generic type).

The second extension method you made:

public static T[] ToArray<T>(this T toConvert) => new[] { toConvert };

Converts any T object to a single object array. Since this is a generic type without an interface, it is preferred over an extension method taking an interface with a generic type. In essence, it is a greater covering surface of potential types to apply the extension on than the interface with a generic type. The compiler will prefer concrete types that match extension methods in favor of interfaces that match.

C# language spec, go about 60% down to find Method Overloading : https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/introduction

C# overload resolution: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.3/improved-overload-candidates

VB version, although applies to C# mostly: https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/language-specification/overload-resolution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM