Wondering why this doesn’t work. Insight appreciated.
static void Main(string[] args)
{
List<int> foo = new List<int> { 1, 2, 3 };
var myResult = MyTest<int>(foo);
}
private static List<int> MyTest<T>(List<T> input)
{
List<int> bar = new List<int> { 2, 3, 4 };
return bar.Where(b => input.Contains(b)).ToList();
}
Expected output from MyTest() is a List { 2, 3 }. However, the compiler reports two errors on input.Contains(b), as follows:
-
Argument 1: cannot convert from ‘int’ to ‘T’
-
The best overloaded method match for ‘System.Collections.Generic.List.Contains(T)’ has some invalid arguments
This Where() clause works fine if I don’t use generic lists.
This is a simplification of my real-world problem, so please don’t get stuck on “why are you writing this?” The problem is the error and why it’s occurring.
Revised for (hopefully) clarity:
namespace SandBox
{
class Foo
{
public int FooInt { get; set; }
public string FooString { get; set; }
}
class Program
{
private static List<Foo> fooList = new List<Foo> {
new Foo() {FooInt = 1, FooString = "A"},
new Foo() {FooInt = 2, FooString = "B"},
new Foo() {FooInt = 3, FooString = "C"}
};
static void Main(string[] args)
{
List<int> myIntList = new List<int> { 1, 2 };
var myFirstResult = GetFoos<int>(myIntList);
List<string> myStringList = new List<string> { "A", "B" };
var mySecondResult = GetFoos<string>(myStringList);
}
/// <summary>
/// Return a list of Foo objects that match the input parameter list
/// </summary>
private static List<Foo> GetFoos<T>(List<T> input)
{
//***
// Imagine lots of code here that I don't want to duplicate in
// an overload of GetFoos()
//***
if (input is List<int>)
{
//Use this statement if a list of integer values was passed in
return fooList.Where(f => input.Contains(f.FooInt));
}
else if (input is List<string>)
{
//Use this statement if a list of string values was passed in
return fooList.Where(f => input.Contains(f.FooString));
}
else
return null;
}
}
}
The same compiler errors are reported on input.Contains(f.Property).
Try this:
The problem is that at the compiler has no idea what type T is. Since T could be anything you can’t call a method which expects an int (
input.Contains).