Implementing traits in C# using Roslyn Source Generators
М. Ю. ПОЗУР, Viktoriia V. Voitko, СВІТЛАНА БЕВЗ et al. · Informatyka Automatyka Pomiary w Gospodarce i Ochronie Środowiska · 2025
The paper presents an approach to implementing traits functionality in the C# programming language through the use of Roslyn Source Generators, a compile-time metaprogramming tool introduced in .NET5. Traits, which are composable units of fine-grained reuse, can benefit the C# language by bringing a mechanism for behavior reuse in the context of single inheritance. The article describes the design and implementation of a source generator that allows to annotate classes with metadata attributes, automatically injecting the corresponding member definitions at compile time. To achieve better code generation performance at design time, Incremental Source Generators were used. The composition of trait members is described in detail, focusing on name conflict resolution and type safety by utilizing interfaces and the override mechanism. Defining non-public members in a context of a trait is also discussed and implemented, thus allowing for better code reusability. The article concludes that language-level features such as traits can be implemented in the C# language by using Roslyn Source Generators, thus demonstrating the potential of such an instrument and metaprogramming in general.
Cited by 0 works. doi:10.35784/iapgos.8488 Open-access PDF
Authors
References
- Traits: Composable Units of Behaviour
- Traits
- Nested Mixin-Methods in Agora
- Stateful Traits
- Empirical assessment of object-oriented implementations with multiple inheritance and static typing
- Applying traits to the smalltalk collection classes
- Traits at work: The design of a new trait-based stream library
- A new modular implementation for stateful traits
- A Comparative Study on the Effect of Multiple Inheritance Mechanism in Java, C++, and Python on Complexity and Reusability of Code
- Separating Use and Reuse to Improve Both