Reputation: 929
I'm doing some practice on linked lists and noticed that it suggests removing and adding a node to update its value. The example below is taken from the MSDN documentation on linked lists:
string[] words = { "the", "fox", "jumps", "over", "the", "dog" };
LinkedList<string> sentence = new LinkedList<string>(words);
sentence.RemoveLast();
sentence.AddLast("yesterday");
Why not just do something like this:
sentence.Last.Value = "yesterday"
This achieves the same output. Or, if the location of dog
is unknown:
sentence.Find("dog").Value = "yesterday";
I can't see what the advantages are to completely removing and then reading the value?
Upvotes: 0
Views: 90
Reputation: 27156
I bethink of 2 advantages.
When call RemoveLast
on an empty list, it tells you The LinkedList is empty., if you use Last.Value
, it will throw NullReferenceException
, which is less readable.
LinkedListNode
is a class, that means if you have kept a reference of the last node, then change Last.Value
will also change its value, usually this behaviour is unexpected.
var last = sentence.Last;
....
....
sentence.Last.Value = "yesterday";
Upvotes: 2
Reputation: 273374
Why not just do something like this:
sentence.Last.Value = "yesterday";
Because that particular page wanted to demonstrate Add and Remove logic.
Upvotes: 2