# How to Implement ECS Archetypes in C#?

I'm trying to figure out how to implement a simple ECS with an Archetype approach, similar to what Unity's ECS uses.

An archetype is just a category for entities that have a specific set of components.

Let's say I had three components, A, B, and C, and I had the following systems:

• System 1 (Archetype requires component A)
• System 2 (Archetype requires components A and B)
• System 3 (Archetype requires components A and C)
• System 4 (Archetype requires components A, B, and C)

Because components could be added and removed from entities on the fly, an entity switches archetypes whenever a component is added or removed.

I'm not quite sure what these archetype collections are supposed to look like. They must be arrays of some kind, but I'm not sure how to store and organize components in them that belong to a specific entity.

My question is, what would this look like in pure, vanilla C# code?

And could generics also help with this?

Those Archetypes are IEnumerable<TComponentKind>, where TComponentKind is what you use to identify components. You can, of course, do better than that. For example, they could be TComponentKind[], or HashSet<TComponentKind>. TComponentKind could be string, Type or even int (and you use bit flags to identify components, in which case the Archetype is also int). Or you might come with something else. That depends on how you implement your ECS.
My toy ECS has the particular quirk that it lets you provide an implementation for custom TComponentKind. Which is likely not something you want in a ECS you use in production. But it means that the code is rather agnostic to that decision, which - I hope - makes for a good case study.