In C# I am trying to write code where I would be creating a Func delegate which is in itself generic. For example the following (non-Generic) delegate is returning an arbitrary string:
Func<string> getString = () => "Hello!";
I on the other hand want to create a generic which acts similarly to generic methods. For example if I want a generic Func to return default(T) for a type T. I would imagine that I write code as follows:
Func<T><T> getDefaultObject = <T>() => default(T);
Then I would use it as
getDefaultObject<string>() which would return null and if I were to write getDefaultObject<int>() would return 0.
This question is not merely an academic excercise. I have found numerous places where I could have used this but I cannot get the syntax right. Is this possible? Are there any libraries which provide this sort of functionality?
Though one might find practical workarounds like Stephen Cleary’s
where you can specify the generics directly, this is a quite interesting problem from a theoretical point that cannot be solved by C#’s current type system.
A type which, as you call it, is in itself generic, is referred to as a higher-rank type.
Consider the following example (pseudo-C#):
In your proposed system, a call could look like that:
But the question is: How do we type the function
Testand it’s argumentf?Apparently,
fmaps every typeTto an arrayT[]of this type. So maybe?But this doesn’t work. We can’t parameterize
Testwith any particularT, sincefshould can be applied to all typesT. At this point, C#’s type system can’t go further.What we needed was a notation like
In your case, you could type
The only language I know that supports this kind of generics is Haskell:
See this Haskellwiki entry on polymorphism about this
forallnotation.