Home > front end >  Using generics and a singly linked list (error CS0311)
Using generics and a singly linked list (error CS0311)

Time:09-17

I have a task to create a collection using a singly linked list and generics. To create a singly linked list I made a special class, nothing unusual.

public class Node<T>
{
    public Node(string name)
    {
        Name = name;
    }
    public string Name { get; set; }
    public Node<T> Next { get; set; }
}

Then I made a short interface where I've wrote all necessary things to work with list. There is some fragment to show:

interface ICustomCollection<T>
{
    void Add(T item);
}

And then I used this interface in a new class of collection:

class MyCustomCollection<T> : ICustomCollection<T> where T: Node<T>
{
    T head;
    T tail;
    T current;
    int count = 0;

    public void Add (T item)
    {
        Node<T> node = new(null);

        if (head == null)
        {
            head = (T)node;
        }
        else
        {
            tail.Next = node;
        }
        tail = (T)node;

        count  ;
        current = tail;
    }
}

Let it be all the functional of the collection. So then I create new class called Person with name:

public class Person
{
    string name;
}

So I need to create a class instance to use the collection:

MyCustomCollection<Person> people;

But now I have a compiler error CS0311 saying that there is no implicit reference conversion from "Person" to 'Node'. I can't really understand what to do with that, I even tried to do something like:

public static explicit operator Node<Person>(Person person)
{
    return new Node<Person>(person.name){ Next = null, Name = person.name };
}

but it doesn't work. Do you have any ideas about that?

CodePudding user response:

You don't want to require that the collection can only contain things that themselves derive from Node<T>. So don't impose that as a requirement. Just use Node<T> internally:

class MyCustomCollection<T> : ICustomCollection<T>
{
    Node<T> head;
    Node<T> tail;
    Node<T> current;
    int count = 0;

At that point, you might also consider moving the Node class inside your collection class and making it private (if you do that, you'd no longer need to parameterise Node itself since it could use the enclosing T parameter of the collection)

You probably also need to make your Node<T> be capable of storing a T as a property.

  • Related