Share via


Sharing .NET generic code under the hood

If you come from a C++ programming background, you are most likely already familiar with C++’s template code bloat problem. Each template instantiation gets its own copy of the code (of course, compiler/linker can optimize by throwing away unused methods). The reason being that C++ template are more like C macro on steriods. I know this is a great simplification, but at the end of the day, it is pretty much a code expansion feature with type safety. This grants C++ some powerful capabilities that C# developers don’t have - like template specialization, or calling arbitary methods on a template class, or a whole different programming paradigm that’s known as template meta-programming. On the other hand, .NET generics require you to define what operations can be perform on T using constraints (otherwise you are limited to a small set of operations such as casts, assignments, etc). However, this does give .NET a unique advantage - it can do a better job at code sharing.

I've moved my blog over to yizhang82.me. You can find the full post here: https://yizhang82.me/dotnet-generics-sharing