Recently I noticed that generic constructed types can be open and closed. But I do not understand what they actually mean. Can you give a simple example?
In practice the terminology doesn't really matter much - I can't remember the last time I had to worry about it except when trying to write about it.
(There are further rules for nested types. Consult the C# 3.0 spec section 4.4 for gory details.)
As an example of an open constructed type, consider:
public class NameDictionary<T> : Dictionary<string, T>
The base class of typeof(NameDictionary<>) is:
T) is an open typeThe MSDN docs for Type.IsGenericType have quite a useful little table.
Just to reiterate, this is almost entirely unimportant in day to day use.
I'm generally in favour of knowing the correct terminology - particularly for things like "pass by reference" etc - but in this case it really, really doesn't come up very often. I would like to actively discourage you from worrying about it :)
From MSDN:
A generic type or method is closed if instantiable types have been substituted for all its type parameters, including all the type parameters of all enclosing types. You can only create an instance of a generic type if it is closed.
So this works as List<int> is closed:
var list = Activator.CreateInstance(typeof(List<int>));
But this throws an exception at run-time because List<> is open:
var list = Activator.CreateInstance(typeof(List<>));
↑
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With