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.
class C<T>
{
}
C<T>
is a constructed type, and an instance type will be created by the process of constructing the type using the type parameters.
C<String> c = new C<String>();
The compiler took the constructed type C<T>
, and using the supplied type parameters an instance type of C<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.
class C
{
public C<T>()
{
}
}
This isn't possible, because you are trying to construct a type that doesn't exist.
C c = new C<String>();
What is the implicit
or explicit
conversion between C
and C<String>
? There is none. It doesn't even make sense.
Because C
is a non-generic type in this example, the instance type is the class declaration itself. So how do you expect C<String>
to construct C
?
The proper declaration for what you want to do is this.
internal class Class<T>
{
private readonly Delegate _delegate;
public Class(Func<T> function)
{
_delegate = function;
}
}
Here because we have a constructed type Class<T>
, the proper instance type can be created by the compiler.
Func<String> function = new Func<String>(() => { return String.Empty; });
Class<String> c = new Class<String>(function);
If you tried to do it the way you want in your question.
Func<String> function = new Func<String>(() => { return String.Empty; });
Class c = new Class<String>(function);
The constructed type would be Class<String>
, which is not the same as type C
, and there is no implicit
or explicit
conversion from either one. If this was allowed by the compiler, C
would be in some unknown and unusable state.
What you do need to know about constructed types, is this.
class C<T>
{
public C<T>()
{
}
}
While you cannot explicitly declare a generic constructor, it is valid but only as a closed type constructor at runtime.
C<String> c = new C<String>();
At compile time, the following constructor is created.
public C<String>()
{
}
Which is why this is valid:
C<String> c = new C<String>(); // We just used the closed type constructor
If what you wanted was allowed, something like this could happen.
class C<T>
{
public C<U>()
{
}
}
// ???
C<String> c = new C<Int32>();
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.