allow type inferencing to support implicit casting operators #3916
-
Should implicit casting operators be added to the logic of performing type inferencing? using System;
static class Program
{
static void Main()
{
int[] values = default;
// no implicit conversion
MethodA(values); // <- works
// implicit conversion
MethodB<int>(values); // <- works
MethodB(values.AsSpan()); // <- works
MethodB(values); // <- does not work (but could work if type inferencing accounted for implicit casting operators)
}
static void MethodA<T>(T[] a) { }
static void MethodB<T>(Span<T> a) { }
} If the compiler doesn't find an exact match, look for the potential for any implicit casting operators and see if there is a single match. If yes, then infer the types to match the result of the implicit casting. One of the downsides is that adding implicit casting operator overloads can break type inferred method calls reliant of a single match from the implicit cast inferred types. However, there is already a precedence for this issue. You can already break calling code by adding method overloads. Here is one example: static class Program
{
static void Main()
{
MethodC<string>(default);
}
static void MethodC<T>(T a = default) { }
//static void MethodC<T>(int a) { } // <- uncomment me and it will break calling code
} That being said, adding implicit casting operators is generally much less common than adding method overloads. So, adding implicit casting operators into type inference logic may not be a horrible idea. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Duplicate of #2067. |
Beta Was this translation helpful? Give feedback.
Duplicate of #2067.