简体   繁体   中英

Why is LinkedListNode Next property readonly?

I've been working on LeetCode problems using Visual Studio IDE and have noticed an issue when trying to set a linkedlistnode's next value to a new node, which is that 'property or indexer ......Next cannot be assigned to -- it is read only' . I can assign a node's next to a node, but cannot assign a node to a node's next. Why is this the case with .NET?

var l1Value = l1 == null ? 0 : l1.Value;
var l2Value = l2 == null ? 0 : l2.Value;
var newNode = new LinkedListNode<int>((l1Value + l2Value + overflow) % 10);
start.Next = newNode; <------ red squiggly
start = start.Next; <------ no red squiggly

You should use AddBefore / AddAfter / AddFirst / AddLast methods on LinkedList to add elements to your list.

I don't know 100% but I assume the API surface does not allow you to modify Next element of a LinkedListNode because that would allow you to end up with weird things like cycles, incomplete lists, etc. Mainly things that make of an inconsistent state. The documentation says LinkedList does not support that:

The LinkedList<T> class does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state. The list remains consistent on a single thread. The only multithreaded scenario supported by LinkedList<T> is multithreaded read operations.

Instead of exposing the low level Next / Previous properties with setters the authors decided it's better to provide methods to accomplish the common insertion/deletion operations and make sure all the right things happen. Eg they make sure both Next and Previous get updated on every insert/delete. If they allowed you to modify Next or Previous directly it wouldn't be possible to make sure both are always updated when necessary. You can still accomplish what you need but they limited the possibility of bugs when people implement these operations themselves.

Next property has only getter that returns the next item from LinkedListNode .

I think you are looking for start.List.AddLast(newNode) .

Hope helps,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM