bagofmilk
bagofmilk

Reputation: 1550

C# Linq Ambiguous call Between System.Linq and System.Collections

There are similar questions to this - but so far none of them helped.

I'm calling:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

Then in a section of my code, VS is pointing out errors in the LINQ methods (.Last() and .Max() ). I hovered over the .Max(). The error says:

The call is ambiguous between the following methods or properties: 'System.Linq.Enumerable.Max(System.Collections.Generic.IEnumerable<int>)' and 'System.Linq.Enumerable.Max(System.Collections.Generic.IEnumerable<int>)'

I've tried re-installing all of my references and packages, I restarted VS, IIS (this is a website). VS recognizes System.Linq so that's not an issue....

I can't figure out why this is all the sudden throwing errors.

enter image description here

Upvotes: 4

Views: 4126

Answers (1)

InBetween
InBetween

Reputation: 32770

This can happen if anywhere in your code or in a referenced assemby someone has had the horrible horrible idea of implementing their own IEnumerable<T> extension methods and not knowing better, used the same namespace as the ones provided by the framework:

  • Alpha assembly rolls their own IEnumerable<T> extension methods in System.Linq namespace:

    namespace System.Linq {
        public static class MyEnumerable {
            public static T Max<T>(this IEnumerable<T> source) { //...
            }
        //... 
        }
    }
    
  • Assembly Charlie thinks Alpha is great due to some other functionality it provides and references it completely oblivious to the nasty surprise it hides inside.

    using System.Linq; //woops
    
    namespace Charlie {
        class C {
            void Foo() {
                var l = new List<object>() { 1, 2, 3 };
                var m = l.Max() /*compile time error. Ambiguous call*/ } }
    }
    

I don't know if this can be your case but its a probable scenario. Another potential candidate could be some versioning conflict but I'm not really sure if that is even possible in VS. I've never run into anything similar with System.* namespaces.

Upvotes: 5

Related Questions