Reputation: 213
Consider this code:
using System.Linq;
namespace ExtensionMethodIssue
{
static class Program
{
static void Main(string[] args)
{
var a = new[] { 1 };
var b = new[] { 1, 2 }.Where(a.Contains).ToList();
var c = new[] { 1, 2 }.Where(i => a.Contains(i)).ToList();
}
}
}
The code compiles successfully. Then I'm adding the nuget package "itext7 7.0.4", and now the compilation fails because of:
//Error CS0122: 'KernelExtensions.Contains<TKey, TValue>(IDictionary<TKey, TValue>, TKey)' is inaccessible due to its protection level
var b = new[] { 1, 2, 3 }.Where(a.Contains).ToList();
// This is still ok.
var c = new[] { 1, 2, 3 }.Where(i => a.Contains(i)).ToList();
The reason is that the itext7 library has an internal class with extension methods in the global namespace (here it is).
internal static class KernelExtensions {
public static bool Contains<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) {
return dictionary.ContainsKey(key);
}
}
For some reason the compiler chooses an inaccessible extension method with an incompatible signature from the global namespace instead of the accessible extension method with a compatible signature from the LINQ namespace.
The question is: is this behavior expected in terms of the language specification or is it a bug in the compiler? And why does it fail only in the case with a "method group" and still work with i => a.Contains(i)
?
Upvotes: 15
Views: 813
Reputation: 12748
That is a compiler bug, an inaccessible function should not affect overload resolution.
As a general workaround use lambdas as an argument instead of a method groups because overload resolution seems to work fine with them. It is not obvious which is faster/more efficient in your particular scenario, micro-optimize as needed using relevant performance metrics.
In this particular case you can also use other extension methods like Enumerable.Intersect()
if you are working with sets, and aren't concerned about duplicates, Enumerable.Join()
or a simple loop.
For more information check:
Upvotes: 3