July 24, 2016

C++/CLI type system as seen from .NET and CIL

For some time now, I have delved, out of necessity, into C++ and all its quirks and secrets. One thing that has always fascinated me in C++ is its marvelously complex type system. In C#, you can mostly just work with arrays, pointers are possible but not recommended, and also generics. C++ has loads of declarators – arrays with fixed size, pointers, references, and this all can be combined with anything else and also qualifiers – mostly const and volatile. These two keywords also exist in C#, but they have vastly different meaning.

Now you may be surprised or not, but all these constructions are actually accurately representable in Common Intermediate Language (CIL for short), the language that separates all .NET languages from native code. Though C# doesn't show the full potential of its type system (however, the newest drafts have quite appealing suggestions, like ref returns), in CIL, the type system is as rich as C++'s, maybe even richer.

C++/CLI is a beautiful and well-designed combination of C++ and .NET, and shall serve as an example of how its types are translated into CIL. If you are not familiar with C++ at all, don't worry, I'll be easy on you. The following descriptions will be mainly from the C# perspective; all in all, that's from whence I come.

Let's start with an overview of what types we'll have to consider: