How to write type-safe loosely coupled components

How does one go in Unity with enforcing type safety while not heavily relying on inheritance, embracing Unity’s component-based architecture?

As a concrete example of what I’m trying to achieve, I have a Unit<T> component which represents units on a strategy game grid where the cells have type T. I also have the Selectable<T> and Movable<T> components. In some specific point of the code, in another component, I have a method which takes a Unit<T> as parameter. I wanted to constrain this parameter to accept only Units which are Movable and Selectable. Is it doable somehow without having to refactor Selectable<T> and Movable<T> into interfaces and creating another component which inherits from Unit<T> and implements the new ISelectable and IMovable, while maintaining the type safety?

Interfaces are great.

You can also use generic type constraints for more control on what you accept as T. This seems like what you want. public class MyGenericClass<T> where T:IComparable { } from where (generic type constraint) - C# Reference | Microsoft Learn

You can also do some nifty tricks with GetComponent and generic types. And of course, since you can figure out the type of T, you can perform different things accordingly.

Finally, you can use Duck Typing in C# through reflection. This is excruciatingly slow.

An opinion comment: These types of patterns are nice but have real impact on your software (duck typing for example). They work best in applications that do not need performance. In a video game, I recommend you take performance into consideration and steer away from runtime reflection if at all possible. Coupling your data and classes to improve performance is a valid option that presents itself to you. And with intelligent field/property/method/class renaming, many gripes of tightly coupled patterns are not an issue anymore.

Cheers :slight_smile: