BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Mixins for C# and Visual Basic

Mixins for C# and Visual Basic

This item in japanese

Mixins are small bits of functionality that are useful to a wide variety of otherwise unrelated classes. In languages that support multiple inheritance mixins are added as secondary base classes while dynamically typed languages simply merge in the extra functionality. Since C# and VB don’t normally support these options, mixins are normally added using base classes that can become bloated or by a lot of copy-and-paste. Composition isn’t much help here, as the mixed-in methods and properties would need to be delegated to the internal object.

The re-mix project offers an alternative. Using runtime code generation, simple classes are combined with one or more mixin classes. While it has the appearance of multiple inheritance it doesn’t actually use it. Instead it uses a combination of object composition and a matching interface.

For example, say you want a mixin that adds deep cloning support to classes. You would create an interface called ICloneable and a matching mixin called CloneableMixin that implements it. CloneableMixin automatically gets a reference to its parent object through which it can perform the cloning operation.

At runtime one can then take arbitrary classes and mix them with the CloneableMixin to create new types. The new type will inherit from the base type and implement all of the interfaces that its mixins implemented. All of these new interface methods will be delegated to instances of the mixins.

Another use of mixins is to override behavior of the base class. Under this model the methods in mixin become overrides for base class methods in the generated class.

You can learn more about re-mix and mixins in general from Stefan Wenig and Fabian Schmied’s Lang.NET presentation.

Rate this Article

Adoption
Style

BT