August Williams
August Williams

Reputation: 929

Why does MSDN suggest adding and removing a linked list node to modify its value?

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

Answers (2)

shingo
shingo

Reputation: 27156

I bethink of 2 advantages.

  1. 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.

  2. 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

Henk Holterman
Henk Holterman

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

Related Questions