I am coming across an error that I have not seen before. I am hoping some one can help.
Here is my code:
public class MyT
{
public int ID { get; set; }
public MyT Set(string Line)
{
int x = 0;
this.ID = Convert.ToInt32(Line);
return this;
}
}
public class MyList<T> : List<T> where T : MyT, new()
{
internal T Add(T n)
{
Read();
Add(n);
return n;
}
internal MyList<T> Read()
{
Clear();
StreamReader sr = new StreamReader(@"../../Files/" + GetType().Name + ".txt");
while (!sr.EndOfStream)
Add(new T().Set(sr.ReadLine())); //<----Here is my error!
sr.Close();
return this;
}
}
public class Customer : MyT
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Item : MyT
{
public int ID { get; set; }
public string Category { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
public class MyClass
{
MyList<Customer> Customers = new MyList<Customer>();
MyList<Item> Items = new MyList<Item>();
}
On the line that says, "Add(new T().Set(sr.ReadLine()));" I get "Error 7, Argument 1: cannot convert from 'Simple_Reservation_System.MyT' to 'T'". Can someone please help me fix this.
Your type MyList can only contain elements of type "T" (specified when the list is declared). The element you are trying to add is of type "MyT", which cannot be downcasted to "T".
Consider the case in which MyList is declared with another subtype of MyT, MyOtherT. It is not possible to cast MyT to MyOtherT.
Because your type
MyT
is not the same that generic parameterT
. When you write thisnew T()
you create an instance of typeT
that must be inherited fromMyT
, but this is not necessarily the type ofMyT
. Look at this example to see what I mean:Your Add parameter takes the generic type T. Your Set method return a concrete class MyT. It is not equal to T. In fact even if you call this:
Add(new MyT())
it will return an error.
I would also like to add that this is an error only while you are inside the MyList class. If you call the same method from a different class it will work.