Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics and inheritance - method args

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.

like image 938
user3378909 Avatar asked Apr 16 '26 14:04

user3378909


2 Answers

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);
like image 132
Eli Arbel Avatar answered Apr 19 '26 04:04

Eli Arbel


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 :)

like image 45
Bas Avatar answered Apr 19 '26 04:04

Bas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!