Share via


The ref type

There are two major CLR types that we expose in Whidbey: ref and value.
I'll talk about ref types here, and about value types later.

So, what is a ref type?   This is the same type that was exposed
in Managed Extensions as __gc
It is implicitly inherited from the CLR base type System::Object and
has access to all of the features in that type.  Let's take a look
at a simple ref type:

  ref class R{

public:

R(int x):i(x){} //constructor

int get(){ return i; } //member
function

private:

int i; //int member

};

That's fairly simple.  In definition, the ref type isn't all that different
from a regular old C++ class.  In fact, for some of your existing C++ classes,
you may be able to slap a ref on the
front and make it into a ref type.

Ref types are allocated on the GC
heap
.  In C++, when you wanted to put something on the native heap, you made
a pointer to it (using the * indirection)
and newed it thusly:

  class N{}; //native
class

N* n = new N; //allocate N on the native heap

Apply the same concepts to ref types, except you use the "handle" indirection ^ ,
instead of the pointer, and instead of using the operator new you
use gcnew, like this:

  ref class R{}; //ref type

R^ r = gcnew R; //allocate R on the gc heap 

This is one of the many simple additions to the C++ language that makes working with
CLR types simple, easy, and straightforward.  It looks a lot like code you're
used to seeing.

Comments