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
Work experience extension methods:
Employee Class:
So we can Simply get Employee Level:
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
Put years of experience set & get extention methods:
now we can update GetTechLevel method to not wait years of experience from client
Now we can get Employee Level:
Output Name Esraa, Level = Junior
Code sample
Advantages
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.
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)
Great effort !
Thanks 😃, I hope it adds value to everyone.