Implementing traits in C# using Roslyn Source Generators

Main Article Content

DOI

Mykhailo Pozur

mixalchik545@gmail.com

Viktoria Voitko

dekanfki@i.ua

https://orcid.org/0000-0002-3329-7256
Svitlana Bevz

bevz.svitlana.v@gmail.com

https://orcid.org/0000-0002-4651-2453
Serhii Burbelo

smburbelo@gmail.com

https://orcid.org/0000-0002-8554-2292
Olena Kosaruk

lena.kosaruk@vntu.edu.ua

https://orcid.org/0000-0003-1346-2944

Abstract

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.

Keywords:

C#, traits, object-oriented programming, metaprogramming, code generation

References

Article Details

Pozur, M., Voitko, V., Bevz, S., Burbelo, S., & Kosaruk, O. (2025). Implementing traits in C# using Roslyn Source Generators. Informatyka, Automatyka, Pomiary W Gospodarce I Ochronie Środowiska, 15(4), 151–157. https://doi.org/10.35784/iapgos.8488