📎 Webclip
Pseudo Traits in C#
The post argues that C# 8.0 interfaces with default implementations resemble traits, but treats that idea as controversial. It then presents a C# 7.0 experiment that uses marker interfaces, an abstract Trait base class, and extension methods to attach behavior to classes without putting code in the classes themselves.
Reading notes#
- C# 8.0 interfaces with default implementations are presented as a bad fit for the idea of an interface.
- Traits are described as a construct that attaches default behavior to objects through the traits they exhibit.
- The examples use
Runner,Swimmer, andFlyeras trait-like behaviors. - Swift is mentioned as a language that fits this style well through protocol extensions.
- The C# experiment starts from shapes that can roll, bounce, or both.
- The pattern uses an abstract
Traitclass andITrait<T>as a filter for trait types. CanRollandCanBounceare defined as trait types.ShapeTraitsaddsRollandBounceextension methods for the matching trait interfaces.Cylinder,Cube, andBallimplement the relevant interfaces and get behavior from the extensions.- The author calls the result “pseudo traits” and presents it as a thought experiment rather than recommended practice.
