CTS and primitive types

There is a hierarchy of classes that should be used to help language interoperability in .NET, it is called CTS (Common Type System) and it is based on the System::Object class. So, anything in CTS is a System::Object.

That means that we can call on any CTS object the System::Object method:
  • ToString;
  • GetType, provides RunTime Type Information (RTTI) in .NET;
  • GetHashCode;
  • Equals.

C++/CLI it is smart enough to use primitive types as managed types, so having a way to work on them as System::Objects.

So this code would output to console System.Int32:

System::Console::WriteLine((42).GetType()); // System.Int32

Here is the mapping the primitive C++ type and the CTS classes that wrap each of them, and some examples of its literal values:

bool System::Boolean (true)
unsigned char System::Byte
signed char System::SByte ('a')
short System::Int16
unsigned short System::UInt16
int System::Int32
unsigned int System::UInt32 (1U)
long long System::Int64 (1LL)
unsigned long long System::UInt64 (1ULL)
float System::Single (1.0f)
double System::Double (1.0)
wchar_t System::Char (L'a')
void System::Void

Even cooler, C++/CLI could use a CTS object as a primitive, when required so, this piece of code works properly:

System::Double PI = 3.14159265358979;
std::cout << PI << std:: endl;

PI is passed to cout as if it were declared as double.

This post is based on my reading on the book "Expert C++/CLI: .NET for Visual C++ Programmers" by Marcus Heege, APress. I suggest you to read it too, to have more details on the matter

No comments:

Post a Comment