Pawan Mishra
Pawan Mishra

Reputation: 7268

Why is LinkedListNode class immutable?

I am curious to know why all the properties(Next, Previous, Value etc) exposed by the LinkedListNode class are readonly i.e. these properties are not having their corresponding setters?

I was trying to solve a small linked list related algorithmic problem and decided to use .Net's built in LinkedList class. But due to readonly behavior of LinkedListNode's class properties, I cannot override the values or change the "Next" pointer of any given node.

Thanks

Upvotes: 7

Views: 1191

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283713

Value does have a setter, the declaration is public T Value { get; set; }.

The lack of setters on Next and Previous prevent you from turning the linked list into a tree or other topology that the LinkedList methods aren't designed to cope with.

The LinkedList class does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state.

You can change these properties by using the list's methods such as AddBefore that preserve the invariants that each LinkedListNode is a member of only one list, node.Next.Previous always points back to node, and there are no cycles, etc.

Upvotes: 7

MarcinJuraszek
MarcinJuraszek

Reputation: 125640

Next/Previous are readonly to make sure that you won't mess up the list structure. You have to use LinkedList<T> methods to modify the list, and they will make sure you won't end up with incorrect state. Letting you change the references would make it possible.

Even though MSDN states, that Value is not settable, if you look at LinkedListNode<T> source code, you'll find that there is actually a setter defined!

// Note following class is not serializable since we customized the serialization of LinkedList. 
[System.Runtime.InteropServices.ComVisible(false)] 
public sealed class LinkedListNode<T> {
    internal LinkedList<T> list;
    internal LinkedListNode<T> next;
    internal LinkedListNode<T> prev;
    internal T item;

    public LinkedListNode( T value) {
        this.item = value;
    }

    internal LinkedListNode(LinkedList<T> list, T value) {
        this.list = list;
        this.item = value;
    }

    public LinkedList<T> List {
        get { return list;}
    }

    public LinkedListNode<T> Next {
        get { return next == null || next == list.head? null: next;}
    }

    public LinkedListNode<T> Previous {
        get { return prev == null || this == list.head? null: prev;}
    }

    public T Value {
        get { return item;}
        set { item = value;}
    }

    internal void Invalidate() {
        list = null;
        next = null;
        prev = null;
    }           
}  

So you should be able to change the value.

Upvotes: 2

Related Questions