Skip to content

[API Proposal]: IsClosedTypeAttribute: add DerivedTypes property #129009

Closed

Description

@RikkiGibson

Background and motivation

Follow up to #128161

Reflection-based components need to be able to identify the set of derived types of a closed type. See #125449.

We discussed how to best make this information available in cc-list-subtypes.md. When we met about this, we leaned against adding a reflection API like Type.GetSameAssemblySubtypes(), in part due to the relatively narrow use case and C#-specific purpose of that API. Instead we settled on listing the derived types in an attribute on the closed type.

API Proposal

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    public sealed class IsClosedTypeAttribute : Attribute
    {
        public IsClosedTypeAttribute() { }
+       public Type[] DerivedTypes { get; set; }
    }
}

API Usage

[IsClosedType] cannot be used explicitly in C#. It is used by the compiler in the following way:

public closed class Animal;
public class Dog : Animal;
public class Cat : Animal;
public class CalicoCat : Cat;

// generates the following metadata:
[IsClosedType(DerivedTypes = [typeof(Dog), typeof(Cat)])]
public class Animal;
public class Dog : Animal;
public class Cat : Animal;
public class CalicoCat : Cat;
// In generic cases, the attribute lists the definitions of the derived types
public closed class C<T>;
public class D1<T> : C<T>;
public class D2<T, U> : C<Dictionary<T, U>>;
public class D3 : C<string>;

// generates the following metadata:
[IsClosedType(DerivedTypes = [typeof(D1<>), typeof(D2<,>), typeof(D3)])]
public class C<T>;
public class D1<T> : C<T>;
public class D2<T, U> : C<Dictionary<T, U>>;
public class D3 : C<string>;

If this API proposal is accepted, then the compiler will always set a value for this property, and the compiler will guarantee that the value will be consistent with the TypeDef table for the containing module. i.e. it will contain the same set of subtype definitions that we would have discovered by scanning the TypeDef table. Note that this doesn't protect us against post-build tools adding new derived types and failing to update the attribute. See also Risks.

Alternative Designs

We might want to make it so tools which use this attribute, are required to specify a value for DerivedTypes. We could consider one of the following to try to emphasize the need to specify a value:

  • Put required modifier on the attribute property. I didn't see any pre-existing example of a public required property in the core libraries, and, this isn't wouldn't be especially "binding" for post-compilation tools, so I didn't suggest this in the main proposal.
  • Change the constructor signature to take a (possibly params) Type[] derivedTypes, and do not include the DerivedTypes.set accessor.

Risks

Quoting cc-list-subtypes.md:

We resisted doing this until now, because we felt the information was redundant. The TypeDef table is already a source of truth for this, and theoretically a type using this encoding could have differences between the table and the attribute.

The risk of having multiple sources of truth for this is: different tools which operate in a similar domain, may end up using different sources for the information. For example, maybe STJ uses the attribute to find the subtypes, and Newtonsoft uses the TypeDef table. This creates an interoperability issue which may or may not amount to a security bug.

Although we assume that the compiler is going to provide a correct list of subtypes in the attribute, post-build rewriting tools might not. The possibility of divergence might further motivate runtime enforcement. For example, throwing InvalidProgramException at runtime, when a subtype is loaded, and its base type has [IsClosedType] attribute, and the attribute doesn't include the subtype.

Moving forward with this API proposal, may motivate us to add a runtime enforcement when a type is loaded, when the base type is a closed type, that:

  1. the derived type is listed in the IsClosedTypeAttribute.DerivedTypes on the base type.
  2. the derived type is declared in the same module as the base type.

Regarding runtime enforcement, there was also a corner case pointed out with type forwarding. It doesn't seem valid/sane to forward a derived type of a closed type to another assembly, because it seems to require declaring the derived type in a different assembly. It feels reasonable to block that.

Activity

  1. added
    untriaged
    on Jun 4, 2026
  2. changed the title [-]IsClosedTypeAttribute: add DerivedTypes property[/-] [+][API Proposal]: IsClosedTypeAttribute: add DerivedTypes property[/+] on Jun 4, 2026
  3. added
    api-suggestion
    and removed
    untriaged
    on Jun 4, 2026
  4. dotnet-policy-service commented on Jun 4, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-runtime-compilerservices
    See info in area-owners.md if you want to be subscribed.

  5. added
    blocking
    api-ready-for-review
    and removed
    api-suggestion
    on Jun 4, 2026
  6. tannergooding commented on Jun 4, 2026

    @tannergooding
    Member

    This was raised as a possibility when we reviewed #128161, so I don't expect any big pushback against it.

  7. jkotas commented on Jun 5, 2026

    @jkotas
    Member

    public Type[] DerivedTypes { get; set; }

    Does this need to be nullable Type{]? ? What are the consumers expected to do when this property is null?

    It may make more sense to go with the constructor argument from the alternative proposals.

    may motivate us to add a runtime enforcement when a type is loaded, when the base type is a closed type

    I do not think we want to be wasting cycles during startup on runtime enforcement.

  8. eiriktsarpalis commented on Jun 5, 2026

    @eiriktsarpalis
    Member

    I missed the previews API review for the attribute, but I will say I'm not a huge fan of the current IsClosedTypeAttribute name, especially now that under this proposal it ceases to be a simple marker. I get that we wanted to preserve ClosedTypeAttribute for other uses, but given that we're dedicating the closed keyword to this feature I fail to see where we might use the term "closed type" elsewhere without introducing confusion.

    @bartonjs @tannergooding thoughts?

  9. eiriktsarpalis commented on Jun 5, 2026

    @eiriktsarpalis
    Member

    public Type[] DerivedTypes { get; set; }

    Does this need to be nullable Type{]? ? What are the consumers expected to do when this property is null?

    I'm assuming it would be treated the same way as an empty array (which canonically represents a closed class without descendants). I think marking it non-nullable is the way to go.

  10. 10 remaining items

  11. bartonjs commented on Jun 8, 2026

    @bartonjs
    Member

    Hopefully you'll agree that when there are two pieces of data representing the same thing, only one is authoritative, and you're reading the other, this is fundamentally a Time-of-Check/Time-of-Use gap. That means, from a security footing, this starts of at negative a trillion or so. The existence of this ToC/ToU introduces the space for other security gap types, such as the aforementioned parser differential.

    Also, from a security perspective, the weakness of something like this isn't the worst thing I can come up with in an hour, it's the worst thing anyone can come up with in the fullness of time.

    If the runtime enforces the correctness of the attribute, ToC/ToU goes away, and the redundant data can be treated as authoritative.

    This attribute is in System.Runtime.CompilerServices namespace. It is meant to be added by compilers.

    The expected use case is useful input into designing the ergonomics of the feature. The security aspects of a feature come from "what if the guard rails are missing?". That means that the security view of this compiler does not come from the Roslyn experience, it come from ilasm.

    in the STJ case, this seems similar to declaring an ordinary class hierarchy, and forgetting to add some [JsonDerivedType] attributes to the base, or accidentally passing typeof() an unrelated type.

    I hope that's not a suggestion that declaring a type closed automatically makes it eligible for JSON polymorphic serialization, because I'll have to be a security nay-sayer on that, too. (If there's a gesture of "Allow all of my closed types in serialization", then, well, OK, but it can't be gesture-free).

    The list of derived types being incomplete. I would consider this a functional correctness problem as opposed to a security problem. It's equivalent to forgetting to add a [JsonDerivedType] annotation for a newly declared type.

    Well, remember, sometimes a lack of a [JsonDerivedType] is intentional. That's why the related-but-different STJ+closed-types enhancement still needs an explicit gesture... just because someone A) does serialization, and B) wants their switch-expression blocks to not need a drain doesn't mean that they want all data serialized. And over-exposed data is a security issue.

    The list of derived types being incomplete.

    Another point that I think is worth making is that even if the list is correct for an assembly, it's not guaranteed to be consistent across assemblies. Adding types to a closed set is a breaking change, but people outside the BCL make breaking changes all the time. Utility assemblies for semi-closed ecosystems, for example (foundational libraries for an enterprise).

    Now, maybe that means that sane components should never use it for a remote assembly, and "never use this for a remote assembly" becomes the message/mantra, at which point this does devolve to "it's about producing local consistency while producing a single compilation output", and maybe a lot of risk goes away. But, I very much see it as "if it's written down, someone will read it and think it's meaningful".


    My feeling of bad is visceral. This redundant data being available creates space for problems. The more secure position is to not write it down. The data being so low level makes it hard to understand actual risks.

    This is a perf enhancement at the risk of (admittedly theoretical) security. What's the perf gain from doing this? What's the clock/cycle tolerance that was exceeded that justifies the need for this?

    The presence of this data makes it such that anything that touches it now needs to answer "what if it's wrong?". I am a huge fan of just taking away that question.

  12. eiriktsarpalis commented on Jun 8, 2026

    @eiriktsarpalis
    Member

    If the runtime enforces the correctness of the attribute, ToC/ToU goes away, and the redundant data can be treated as authoritative.

    That's not really an option given we're targeting older runtimes.

    I hope that's not a suggestion that declaring a type closed automatically makes it eligible for JSON polymorphic serialization, because I'll have to be a security nay-sayer on that, too. (If there's a gesture of "Allow all of my closed types in serialization", then, well, OK, but it can't be gesture-free).

    The proposed gesture is an InferedDerivedTypes flag, but applying a polymorphism convention for closed types specifically is also on the table: #129041

    My feeling of bad is visceral. This redundant data being available creates space for problems. The more secure position is to not write it down. The data being so low level makes it hard to understand actual risks.

    If you look at what the STJ generator does (and what most generated serializers do for that matter) is emitting redundant models that emulate System.Type and System.Reflection.PropertyInfo that happen to work well in Native AOT. This creates exactly the kind of consistency problem you're describing. If the concern is having that redundancy in the C# compiler's code generation, we could instead move it over to the source generator. However, supporting the same feature in the reflection-based serializer would require running expensive queries at startup.

  13. bartonjs commented on Jun 8, 2026

    @bartonjs
    Member

    If the concern is having that redundancy in the C# compiler's code generation, we could instead move it over to the source generator.

    I prefer that, because now it can be analyzed as an STJ feature, with understood risks.

    supporting the same feature in the reflection-based serializer would require running expensive queries at startup

    So? It seems pretty opt-in, it's one-time expense, and "expensive" is still going to be pretty fast.

  14. jkotas commented on Jun 8, 2026

    @jkotas
    Member

    there are two pieces of data representing the same thing

    It is very common for binaries to contain duplicated data optimized for different use cases. It is the case for both in .NET and non-.NET binaries. The tooling used to produce the binaries must ensure that the duplicate data are self-consistent.

    Time-of-Check/Time-of-Use

    According to Wikipedia, Time-of-Check/Time-of-Use is a race condition. Race conditions require two components running in parallel. It is not the case here. We are worried about serial execution of a tool that produces corrupted binary.

  15. bartonjs commented on Jun 16, 2026

    @bartonjs
    Member

    Video

    We discussed an optional property vs a ctor parameter, and decided optional property (as proposed) is fine.

    namespace System.Runtime.CompilerServices
    {
        public partial class IsClosedTypeAttribute : Attribute
        {
            public Type[] DerivedTypes { get; set; }
        }
    }
  16. added
    api-approved
    and removed
    blocking
    api-ready-for-review
    on Jun 16, 2026
  17. locked and limited conversation to collaborators on Jul 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

api-approvedarea-System.Runtime.CompilerServices

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions