Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case-Insensitive List.Contains(): No overload for method 'Contains' takes 2 arguments

Tags:

c#

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);
like image 654
Lydon Ch Avatar asked Dec 24 '22 00:12

Lydon Ch


1 Answers

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.

like image 172
Selman Genç Avatar answered Jan 31 '23 12:01

Selman Genç