There are type parameters for methods. Why there are no type parameters for constructors?
Example
I think there are several (not many) examples where it would be usefull. My current problem was following:
internal class ClassA
{
private readonly Delegate _delegate;
public ClassA<T>(Func<T> func)
{
_delegate = func;
}
}
A Delegate is enough for my class. But to pass it as method group I need to define the parameter as a Func<T>.
After reading the C# specification it actually does make sense, but it can be confusing.
Each class has an associated instance type, and for a generic class declaration the instance type is formed by creating a constructed type from the type declaration, with each of the supplied type arguments being the corresponding type parameter.
C<T>is a constructed type, and an instance type will be created by the process of constructing the type using the type parameters.The compiler took the constructed type
C<T>, and using the supplied type parameters an instance type ofC<String>was created. Generics is only a compile time construct, everything is executed in the terms of closed constructed types at runtime.Now let’s take your question and put it to the test here.
This isn’t possible, because you are trying to construct a type that doesn’t exist.
What is the
implicitorexplicitconversion betweenCandC<String>? There is none. It doesn’t even make sense.Because
Cis a non-generic type in this example, the instance type is the class declaration itself. So how do you expectC<String>to constructC?The proper declaration for what you want to do is this.
Here because we have a constructed type
Class<T>, the proper instance type can be created by the compiler.If you tried to do it the way you want in your question.
The constructed type would be
Class<String>, which is not the same as typeC, and there is noimplicitorexplicitconversion from either one. If this was allowed by the compiler,Cwould be in some unknown and unusable state.What you do need to know about constructed types, is this.
While you cannot explicitly declare a generic constructor, it is valid but only as a closed type constructor at runtime.
At compile time, the following constructor is created.
Which is why this is valid:
If what you wanted was allowed, something like this could happen.
You can see the problems now that would arise if the construct was allowed. Hopefully this sheds some insight, the specification is rather long and there are many many many sections that cover generics, type parameters, constructed types, closed and open types, bound and unbound.
It can get very confusing, but its a good thing that this isn’t allowed by the compiler rules.