docs.microsoft.com: "Because a generic type definition is only a template, you cannot create instances of a class, structure, or interface that is a generic type definition." so how come I can write this: Dictionary<int, string> d = new Dictionary<int, string>();
or it is not an instantiation? so what am I doing then?
CodePudding user response:
The docs are referring to the so called open generic types. I.e. you can't instantiate Dictionary<,>
, you need to provide both generic type parameters, which results in so called closed (or constructed) generic type (i.e. Dictionary<int, string>
in your case) which can be instantiated.
From Open and closed types docs:
All types can be classified as either open types or closed types. An open type is a type that involves type parameters. More specifically:
- A type parameter defines an open type.
- An array type is an open type if and only if its element type is an open type.
- A constructed type is an open type if and only if one or more of its type arguments is an open type. A constructed nested type is an open type if and only if one or more of its type arguments or the type arguments of its containing type(s) is an open type.
A closed type is a type that is not an open type.
CodePudding user response:
It is an instanciation. When you do
Dictionary<int, string> d = new Dictionary<int, string>()
, you instanicate Dictionary<TKey,TValue>
with TKey : int
and TValue : string
.
What you cannot do is Dictionary d = new Dictionary()
which should return the error you are describing.