Confused about namespaces and overload resolution #48454
Unanswered
thomaslevesque
asked this question in
Q&A
Replies: 2 comments
-
OK, answering my own question. I found the relevant section in the C# 5 spec (since no spec is available for later versions), §7.6.5.2:
This behavior was surprising to me, but it's working as specified. |
Beta Was this translation helpful? Give feedback.
0 replies
-
(And it should have been a discussion rather than an issue... Sorry about that, I'm not yet used to the new discussions feature.) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I just noticed something really weird.
I maintain a library that provides extension methods to
IEnumerable<T>
. This library exposes aToHashSet
method. Everything worked fine, untilEnumerable.ToHashSet
was also introduced innet472
,netcoreapp2.0
andnetstandard2.1
. Predictably, this caused an ambiguous invocation error when both the Linq.Extras and System.Linq namespaces were imported. So far so good, it makes sense.I set out to fix the issue in my library by adding additional targets without the
ToHashSet
method, but then I realized something strange: I should have encountered the problem in my tests, but I didn't. My tests target multiple TFMs, includingnetcoreapp2.0
, and look roughly like this:Notice that in this test, both
System.Linq.Enumerable.ToHashSet
andLinq.Extras.XEnumerable.ToHashSet
are in scope. So I should get an ambiguous invocation error... But I don't! It always usesLinq.Extras.XEnumerable.ToHashSet
.The only reason I can think of is that the test namespace (
Linq.Extras.Tests
) is "under" the namespace the contains the extension method (Linq.Extras
). And indeed, if I change the test namespace toFoo
and add ausing Linq.Extras
, I get the expected error.So, is this behavior expected? Is there an overload resolution rule that prioritizes extension methods in a parent namespace? Where is this rule mentioned?
Beta Was this translation helpful? Give feedback.
All reactions