I've seen various questions regarding if mixins can be created in C# and they are often directed to the re-mix project on codeplex. However, I don't know if I like the "complete interface" concept. Ideally, I would extend a class like so:
[Taggable] public class MyClass { .... }
By simply adding the Taggable interface, I can create objects of type MyClass via some kind of object factory. The returned instance would have all the members defined in MyClass as well as all members provided by adding the tagging attribute (like a collection of tags). It seems like this would be easily doable using C# 4.0 (the dynamic keyword). The re-mix project uses C# 3.5. Does anyone have any good ways to extend objects via C# 4.0 without altering the classes themselves? Thanks.
You can implement mixins in C++ by using CRTP. A prominent example is the class std::enable_shared_from_this .
Definition. 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.
mixin gives a way to add functionality in a class, i.e you can interact with methods defined in a module by including the module inside the desired class. Though ruby doesn't supports multiple inheritance but provides mixin as an alternative to achieve that.
Mixins are sometimes described as being "included" rather than "inherited". In short, the key difference from an inheritance is that mix-ins does NOT need to have a "is-a" relationship like in inheritance. From the implementation point of view, you can think it as an interface with implementations.
You can create mixin-like constructs in C# 4.0 without using dynamic, with extension methods on interfaces and the ConditionalWeakTable
class to store state. Take a look here for the idea.
Here's an example:
public interface MNamed { // required members go here } public static class MNamedCode { // provided methods go here, as extension methods to MNamed // to maintain state: private class State { // public fields or properties for the desired state public string Name; } private static readonly ConditionalWeakTable<MNamed, State> _stateTable = new ConditionalWeakTable<MNamed, State>(); // to access the state: public static string GetName(this MNamed self) { return _stateTable.GetOrCreateValue(self).Name; } public static void SetName(this MNamed self, string value) { _stateTable.GetOrCreateValue(self).Name = value; } }
Use it like this:
class Order : MNamed { // you can list other mixins here... ... } ... var o = new Order(); o.SetName("My awesome order"); ... var name = o.GetName();
The problem of using an attribute is that you can't flow generic parameters from the class to the mixin. You can do this with marker interfaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With