Typeof gives a Type expected exception for an unstructured nested generic type

Usually getting an unconfigured generic type is pretty simple using typeof :

Type genericType = typeof( Func<> ); 

I would expect the following to work, but it gives a Type expected compiler error.

 Type genericNestedType = typeof( Func<Func<>> ); 

It is relatively easy to get around this using Func<Func<object>> . However, when you “consume” a type, you must remember that you call GetGenericTypeDefinition() .

The scenario in which you want to "populate" all unassigned type type parameters is not possible. Again, it would be relatively easy to create a dummy type to specify these parameters. (e.g. Func<Func<ToReplace, object, int>> )

Is there a reason typeof doesn't work on nested unstructured types?

+6
source share
2 answers

I do not believe that this is a compiler error - section 7.6.11 of the C # 4 specification ( typeof operator) does not seem to provide any syntax that would lead it to action; Func<Func<>> is neither a valid type construct nor a valid name construct without a type name.

Regarding the case, though: I assume it is very rarely necessary (I didn’t even think about using it before, and I didn’t hear anyone ask for it), and therefore there is additional complexity in the language design, implementation and testing of the compiler considered to outweigh the benefits. This often happens with the question "why does C # have no X function," as Eric Lippert likes to point out :)

I was pleasantly surprised to see that this can be done at runtime:

 Type unbound = typeof(Func<>); Type partiallyBound = unbound.MakeGenericType(new[] { unbound }); Console.WriteLine(partiallyBound); 

I expected it to be invalid on a system like .NET, although I expect this to cause other problems.

+6
source

The main reason I suspect is simply because typeof( Func<Func<>> ) not very useful. This is not a fully constructed type, so you cannot use it for anything - nor is it a definition of a generic type, therefore you cannot call MakeGenericType(...) to add T external type - it is an internal type that needs T so you need to do something like:

 var closedType = type.GetGenericTypeDefinition().MakeGenericType( type.GetGenericTypeArguments().MakeGenericType(finalT) ); 

So simple ... no real use in typeof(Func<Func<>>) - it's easier to start from scratch.

0
source

Source: https://habr.com/ru/post/900804/


All Articles