DEV Community

Cover image for Mixin in C#
Refaat Elabd
Refaat Elabd

Posted on • Edited on

Mixin in C#

In this post I will talk about Mixin concept and how to implement it in C# and I provide a code example to prove concept, So let's go ahead.


Mixins are a language concept that allows a programmer to inject some code into a class. Mixin programming is a style of software development, in which units of functionality are created in a class and then mixed in with other classes but which cannot itself be instantiated.

  • Mixins are useful in object oriented languages which only support single inheritance Like C#, Java, Kotlin, etc.

  • A mixin class acts as the parent class, containing the desired functionality.

  • In order to implement a mixin in c# we will use a combination of interfaces and extension methods.


Let's dive into an example:

Consider the Employee Class that is a Person needs to use work experience functions

interface to extend functionality from

Work experience extension methods:

Work experience extension methods

Employee Class:

Employee class

So we can Simply get Employee Level:

Client Using
output: Name Refaat, Level = Junior


Does this mean that mixins can only have methods - what about fields?

  • No, they can have fields. To do that we may apply a nested class contains needed fields and then associate the instance of this nested class with each object which implements the mixin interface.

will use ConditionalWeakTable collection to associate mixin classes with fields in the example to let garbage collector cleaning up these Fields.

know more about ConditionalWeakTable

Final example:

  • Let's establish fields at WorkExperienceProvider static class that contains extention methods

Establish Fields

Put years of experience set & get extention methods:
years of experience set & get extention methods

now we can update GetTechLevel method to not wait years of experience from client

GetTechLevel method

Now we can get Employee Level:

Client Using

Output Name Esraa, Level = Junior

Code sample

Whole Code Example

Advantages

  1. It provides a mechanism for multiple inheritance by allowing one class to use common functionality from multiple classes, but without the complex semantics of multiple inheritance.

  2. Code reusability: Mixins are useful when a programmer wants to share functionality between different classes. Instead of repeating the same code over and over again, the common functionality can simply be grouped into a mixin and then included into each class that requires it.

Run code and trace it to more illustration, Have fun

Top comments (2)

Collapse
 
shabaneita profile image
Shaban Eita

Great effort !

Collapse
 
refaatelabddev profile image
Refaat Elabd

Thanks πŸ˜ƒ, I hope it adds value to everyone.