C# Case-Insensitive List.Contains(): No overload for method 'Contains' takes 2 arguments
Got compiler error if we do
list.Contains(stringToSearchDynamic.ToString(), StringComparer.OrdinalIgnoreCase)
But compiles OK if we put actual string
list.Contains(stringToSearch, StringComparer.OrdinalIgnoreCase)
Is this a compiler bug ?
Code:
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
string stringToSearch = "OnE";
dynamic stringToSearchDynamic = "OnE";
//compiles OK
bool isContained = list.Contains(stringToSearch, StringComparer.OrdinalIgnoreCase);
//Does NOT compile
isContained = list.Contains(stringToSearchDynamic.ToString(), StringComparer.OrdinalIgnoreCase);
The type of a dynamic
expression is also dynamic. Since you have a dynamic variable the type of variable.ToString
is resolved at runtime, not at compile time. So it's treated as dynamic
and compiler can't find a Contains
method that takes dynamic
as first argument.
You can cast to string
as suggested in the comments, it works because casting is a compile-time thing and makes the compiler treat your variable as string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With