I've been reading a little of the code in the .Net core project that's just been released by Microsoft. (https://github.com/Microsoft/dotnet) It's nice to be able to see how the .Net core team have implemented things and I thought I might be able to learn a thing or two from their code.
One thing that caught my attention was how the function for Clear() has been implemented.
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly ImmutableList<T> Empty = new ImmutableList<T>();
public ImmutableList<T> Clear()
{
Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableList<T>>().IsEmpty);
return Empty;
}
It appears to me that when you make a new list, the empty property is populated with a new list and this is then returned when the Clear function is run; thereby dereferencing the old list (if you were to say: var students = students.Clear();) and allowing the GC to clear up the old list.
All of which is very cool, what I don't understand is how does the above definition for the Empty property not cause an infinite loop? If every time you create a new list, it in effect actually makes two, then does that not mean that the new ImmutableList instantiated for the Empty property list also instantiates another for it's Empty property and so on and so forth?
Can someone explain please? Also please correct me if my understanding above isn't correct.
Empty
is static and thus only created once. Since it's immutable it doesn't matter that it returns the same instance to anyone that calls Clear
.