2012-10-07

True polymorphic functions in C#

If you ever saw Haskell polymorphic functions you'll never forget that great feeling of full abstraction from who may implement typeclasses that you restrict your argument/result on. Of course OOP gives opportunity to taste some bit of that feeling when we create functions which works with base types and they naturally handles all descendant, but the way they do it is run-time polymorphism and for C# that always require heap allocated objects. Sample in this post doesn't produce box/unbox even in IL while leaving structs private (and thus in maintainable state). After JIT/AOT even if code is in separate assemblies Main() from app will cause specialization of VisitAll from library which will cause specialization of PokeVisitor from app.