I've been working on LeetCode problems using C# 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 read from node's next, 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 byLinkedList<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. E.g. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With