Candy Chiu
Candy Chiu

Reputation: 6679

C# ambiguous extension methods

LinqKit has an extension method ForEach for IEnumerable which clashes with System.Collections.Generic.IEnumerable.

Error   4   The call is ambiguous between the following methods or properties: 
'LinqKit.Extensions.ForEach<Domain>(System.Collections.Generic.IEnumerable<Domain>, System.Action<Domain>)' 
and 
'System.Linq.EnumerableExtensionMethods.ForEach<Domain>(System.Collections.Generic.IEnumerable<Domain>, System.Action<Domain>)'

How can I get rid of this error?

Upvotes: 14

Views: 9117

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564931

Enumerable, in the framework, does not declare an extension for ForEach(). Both of these are from external references.

You should consider only using one of them - either the reference that's adding EnumerableExtensionMethods or the LinqKit.

(This, btw, is one reason that using the same namespace as the framework causes problems - in this case, the author of EnumerableExtensionMethods placed it in System.Linq, which is going to cause an issue any time you're using Linq and you have a namespace clash.)

If you truly need to use this method, then you'll have to call it directly instead of using the extension method, ie:

LinqKit.Extensions.ForEach(collection, action);

Or:

System.Linq.EnumerableExtensionMethods.ForEach(collection, action);

That being said, I would personally just use a foreach loop to process the elements.

Upvotes: 23

Widor
Widor

Reputation: 13285

You simply need to fully-qualify the method that you're calling, as in the error message.

So, instead of using

ForEach<Domain>( ... );

use

LinqKit.Extensions.ForEach<Domain>( ... );

Upvotes: 0

Related Questions