Managed array syntax in C++/CLI

C++/CLI supports managed arrays using a far more intuitive syntax than which existed in the older syntax. Here are some of the basic features of managed arrays in C++/CLI :-

  • Syntax resembles that of C++ templates
  • System::Array is abstract base type for all managed arrays
  • Allocated on the CLR heap (means they get GC’d)
  • Rank of the array need not be 1
  • Implicit conversion to and explicit conversion from System::Array
  • The rank and dimensions of an array object cannot be changed

Pseudo-template of an array type

The declaration and usage of array types in C++/CLI seems to use an imaginary template type (there is no such template of course, it’s all VC++ compiler magic)

namespace stdcli::language
    template<typename T, int rank = 1>
        ref class array : System::Array {};

Sample array usage

These samples show some code snippets that demo how to use single-dimensional and multi-dimensional arrays with C++/CLI

ref class R
    // Single dim array of ref type
    void funcsdref()
        array<String^>^ strarray =
            gcnew array<String^>(5);
        for(int i=0; i<5; i++)
            strarray[i] = String::Concat("Str ",i.ToString());
        for(int i=0; i<5; i++)

    //Single dim array of value type
    void funcsdval()
        array<int>^ strarray = gcnew array<int>(5);
        for(int i=0; i<5; i++)
            strarray[i] = i * 10;
        for(int i=0; i<5; i++)

    //Multi dim array of ref type
    void funcmdref()
        array<String^,2>^ cricketerarray =
            gcnew array<String^,2>(3,2);

        cricketerarray[0,0] = "Sachin Tendulkar";
        cricketerarray[0,1] = "India";
        cricketerarray[1,0] = "Shane Warne";
        cricketerarray[1,1] = "Australia";
        cricketerarray[2,0] = "Shoaib Akhthar";
        cricketerarray[2,1] = "Pakistan";


        for(int i=0; i<3; i++)
            for(int j=0; j<2; j++)
                Console::Write("{0} \t",cricketerarray[i,j]);

Jagged arrays

C++/CLI makes it really easy to declare and use jagged arrays. See my earlier blog entry for the syntax :-


One thought on “Managed array syntax in C++/CLI

  1. Wondering whether I should expand on this blog entry and write an article on managed arrays 🙂

    Blog entries are cool for that. Like, when you think of writing an article, it seems a big task, but then make a blog entry or two on a particular subject and suddenly you find that you have just about 60-70% of required material for the article.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s