Proposal: open generic type support for generic attributes #8198
Unanswered
hez2010
asked this question in
Language Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Open generic type in generic attributes
Summary
Enable open generic types as type arguments in generic attributes.
Motivation
Allowing open generic types in generic attributes can enable many scenarios which are not possible or hard to do today.
One of those scenarios is extension type erasure codegen as proposed in #8194, with open generic types, extension types can be lowered to a generic attribute with its underlying type to allow consuming:
Proposal
Allowing to use type parameter of a type or method in generic attributes:
The codegen strategy is straightforward: emit
!T
and!!U
for the corresponding generic arguments.Considerations
Compatibility
It's completely expressible with today's metadata, and already supported by coreclr.
Runtime changes
This doesn't require a runtime change in the native side. We only need to alter
System.Private.CoreLib
to make it pass the generic context while getting attributes.The runtime needs to skip instantiating a generic attribute if generic context is not provided, that is,
typeof(Foo<>).GetCustomAttributes()
will return an empty array, whiletypeof(Foo<int>).GetCustomAttributes()
will return an array containingAttrAttribute<int>
. This doesn't affactGetCustomAttributesData
asGetCustomAttributeData
is not trying to instantiating an attribute, instead it load data from the metadata directly, sotypeof(Foo<>).GetCustomAttributesData()
will return an array containing the attribute data ofAttrAttribute<T>
.Such changes have been implemented in dotnet/runtime#103213, which is a trivial change for the runtime.
Concern
Unfortunately, we cannot get an attribute instance with open generic types from a generic parameter:
Today we can only get an attribute instance from a generic parameter directly, which means we need to call
GetCustomAttributes()
on a generic argument of a generic type definition or a generic method definition. In this case the generic context is stripped so that we cannot instantiate the attribute with open generics here (because we don't have the generic instantiation).While this doesn't affect
GetCustomAttributesData()
as it doesn't instantiate the attribute instance.If this is not acceptable, we may need to introduce some new overloads for
GetCustomAttributes
to allow passing the generic instantiations manually.Beta Was this translation helpful? Give feedback.
All reactions