Are pointers allowed in an immutable object?
Dictionary keys in C# (probably in most languages) must be immutable.
I consider now the possiblity to make the value of my key to depend on some property of another object.
Generally speaking an immutable object could have a pointer to another object - or not?
When I change this other object, the immutabl开发者_运维问答e object didn't change it's state. But it's behaviour may be different now.Is this allowed for immutable objects?
Is it considered bad practice or on the contrary good practice?You can have pointers in an immutable object, it's the difference between shallow vs deep immutability.
Have a look at the MSDN blog post Immutability in C# Part One: Kinds of Immutability
There is nothing wrong with having an object hold an immutable reference to a mutable object. Indded, that can sometimes be a useful pattern. For example, a collection might expose numerous methods of enumeration. The simplest way to achieve this may be to define a number of structures each of which holds one item: a reference to the collection, and implements IEnumerable.GetEnumerator by calling an appropriate method in the collection. For example, a structure MyMultiSortedKeyDictionary.EnumeratorByFirstKey would hold a reference to a MyMultiSortedkeyDictionary and implement IEnumerable.GetEnumerator by calling GetFirstKeyEnumerator on the root collection. A structure .EnumeratorBySecondKey would be similar, but would call GetSecondKeyEnumerator. Both structures would be immutable, but each would hold a reference to a mutable object.
精彩评论