Why do I need to use a dynamic object when calling IEnumerable.Contains ()?

I try to call IEnumerable.Contains() with a dynamic argument, but I get an error

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

I noticed that I can either apply the argument to the correct type, or use the base type of the collection to fix this problem. But I'm not sure why I cannot just pass 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 
+5
source share
1 answer

Enumerable.Contains is an extension method, and extension methods are not allowed by the mini-compiler that is used at run time. (Extension methods depend on using directives that are not saved. They could have been, but I think it was a little painful.) This includes using dynamic arguments for extension methods as well as using extension methods as their β€œtarget” .

Just specify the extension method directly:

 var result = Enumerable.Contains(ie, d); 
+5
source

Source: https://habr.com/ru/post/1235384/


All Articles