Reputation: 4082
According to both the documentation and metadata for .Net's LinkedListNode<T>
class, its List
, Next
and Previous
properties are get-only. However, LinkedList<T>
somehow manages to alter these properties.
How does LinkedList<T>
achieve this?
Is it using reflection or is it cheating by using internal setters?
Upvotes: 0
Views: 219
Reputation: 1
One can always change data within the same class even if its get-only property
Refer to below example:
class Property
{
private string _name = "_name";
public string Name
{
get
{
return _name;
}
}
public void Foo()
{
_name = "foo";
}
static void Main(string[] args)
{
Property prop = new Property();
Console.WriteLine(prop.Name); // prints _name
prop.Foo();
Console.WriteLine(prop.Name); // prints foo
}
}
Upvotes: -1
Reputation: 1536
The fields list
, prev
and next
in LinkedListNode<T>
are marked with the internal access modifier. Internal types/members are accessible only to other types in the same assembly. In this case, both LinkedListNode<T>
and LinkedList<T>
are in the System assembly.
If we look at how they are actually defined:
public sealed class LinkedListNode<T>
{
internal LinkedList<T> list;
internal LinkedListNode<T> next;
internal LinkedListNode<T> prev;
internal T item;
....
}
Upvotes: 1
Reputation: 51380
Here are the fields of LinkedListNode<T>
:
public sealed class LinkedListNode<T> {
internal LinkedList<T> list;
internal LinkedListNode<T> next;
internal LinkedListNode<T> prev;
internal T item;
// ...
}
As you can see, the fields are internal, and as such they can be manipulated by the LinkedList<T>
(or by any other class in the System
assembly for that matter), but you can't do that from your code.
private void InternalInsertNodeBefore(LinkedListNode<T> node, LinkedListNode<T> newNode) {
newNode.next = node;
newNode.prev = node.prev;
node.prev.next = newNode;
node.prev = newNode;
version++;
count++;
}
Upvotes: 2