5

I am trying to call IEnumerable.Contains() with a dynamic argument, but I am getting the error

'IEnumerable' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains(IQueryable, TSource)' has some invalid arguments

I've noticed that I can either cast the argument to the correct type, or use an underlying collection type to fix the issue. But I'm not sure why I can't just pass in the argument directly.

dynamic d = "test";
var s = new HashSet<string>();
IEnumerable<string> ie = s;

s.Contains(d);           // Works
ie.Contains(d);          // Does not work
ie.Contains((string)d);  // Works
Kris Harper
  • 5,672
  • 8
  • 51
  • 96

1 Answers1

6

Enumerable.Contains is an extension method - and extension methods aren't resolved by the mini-compiler which is used at execution time. (Extension methods depend on using directives, which aren't preserved. They could be, but I guess that was seen as a bit painful.) This includes both using dynamic arguments to extension methods, and on using them as the "target" of extension methods.

Just specify the extension method directly instead:

var result = Enumerable.Contains(ie, d);
Søren Boisen
  • 1,669
  • 22
  • 41
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • This works on this [online compiler](https://dotnetfiddle.net/xPvF8e). – ryanyuyu Nov 06 '15 at 17:50
  • @ryanyuyu no it doesn't it throws an error notice the squiggly red line when you hover over `b = ie.Contains(d);` when clicking on the link – MethodMan Nov 06 '15 at 17:52
  • @MethodMan and notice that was the OP's original code producing the squiggly. Jon Skeet's solution does not produce an error. – ryanyuyu Nov 06 '15 at 17:54