I have a custom interface. I am design a function that takes an argument which is a list. When I pass an argument that is a list of a class that meets this interface, I get an error. Example code below:
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
TestClass A = new TestClass();
A.Name = "A";
TestClass B = new TestClass();
B.Name = "B";
TestClassList aList = new TestClassList();
aList.myList.Add(A);
aList.myList.Add(B);
PrintTestClass(aList.myList);
}
public static void PrintTestClass(List<ItestInterface> TestList)
{
foreach (ItestInterface i in TestList)
Console.WriteLine(i.Name);
}
}
interface ItestInterface
{
string Name { get; set; }
}
class TestClass : ItestInterface
{
public string Name { get; set; }
public string otherVar { get; set; }
}
class TestClassList
{
public List<TestClass> myList;
public TestClassList()
{
myList = new List<TestClass>();
}
}
Here, my calling of "PrintTestClass" calls an error that it cannot convert List<TestClass>
to List<ItestInterface>
. I try to cast it, still doesn't work. What am I doing wrong?