Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cannot inherit LinkedListNode<T>?

In .NET 3.5, I am using the LinkedList class but I am having the following issue. I want the items of that list to be aware of the previous and next items in the list. In other words, I want the method in the items to be able to do this.Next, this.Previous. Is this possible? Below is an example of what I would like to do.

Day d1 = new Day();
Day d2 = new Day();
LinkedList<Day> days = new LinkedList<Day>();
days.AddLast(d1);
days.AddLast(d2);

// Here is want I would like to do
d1.Next = ...

Thanks!

like image 927
Martin Avatar asked Aug 25 '09 23:08

Martin


3 Answers

First, LinkedListNode is sealed so it can not be inherited.

Secondly, LinkedListNode does contain properties Previous and Next that refer to the previous and next nodes in the LinkedList that a given instance of LinkedListNode came from.

Lastly, to use AddLast correctly, you must do the following:

Day d1 = new Day();
Day d2 = new Day();
LinkedList<Day> days = new LinkedList<Day>();
LinkedListNode<Day> node1 = days.AddLast(d1);
LinkedListNode<Day> node2 = days.AddLast(d2);

// now node1.Next refers to node containing d2
// and node2.Previous referes to node containing d1
like image 71
jason Avatar answered Nov 17 '22 03:11

jason


You're using it wrong.

The .AddLast(T) method returns a linked list node. This points to your day and has the prev and next functions you are looking for.

like image 2
Spence Avatar answered Nov 17 '22 03:11

Spence


According to the MSDN, the LinkedListNode class cannot be inherited.

Michael points out that this blog post from Eric Lippert talks about why many classes in the framework are sealed

like image 1
Dan McClain Avatar answered Nov 17 '22 03:11

Dan McClain