I have written data structure LinkedList with method Add:
public class LinkedList<T>
{
private Element<T> first;
private Element<T> last;
public bool Add(Element<T> element)
{
...
I also have defined three classes:
public class Element<T> : IDisposable
public class ElementString : Element<string>, ICloneable
public class ElementLong : Element<long>, ICloneable
When I want to do something like this in main method:
LinkedList<ElementLong> test = new LinkedList<ElementLong>();
ElementLong elem1 = new ElementLong();
test.Add(elem1);
I get the error that method Add "has some invalid arguments". How to solve that problem? Thank you for your help.
When you write
LinkedList<ElementLong>
You define T as ElementLong. The Add method expects an Element<T>, which in this case is
Element<ElementLong>
If you want your list to allow only longs, you can use:
LinkedList<long> test = new LinkedList<long>();
ElementLong elem1 = new ElementLong();
test.Add(elem1);
Also, there's probably no need for the element derived classes, and you can use the base class directly:
var test = new LinkedList<long>();
var elem1 = new Element<long>();
test.Add(elem1);
You should keep the generic type argument of the linked list to the actual type:
LinkedList<long> test = new LinkedList<long>();
ElementLong elem1 = new ElementLong();
test.Add(elem1);
Since ElementLong is actually a Element<long> this will work.
A LinkedList<ElementLong> will expect an Element<ElementLong> as argument, if you still get it :)
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