New Syntax C++ in .NET Version 2

by Richard Grimes



Listing One



generic <class T>

ref class Test

{

   T t;

public:

   Test(T a)

   {

      t = a;

   }

   String^ ToString() override

   {

      return String::Format("value is {0}", t->ToString());

   }

};

void main()

{

   Test<int>^ t1 = gcnew Test<int>(10);

   Console::WriteLine(t1);

   Test<String^>^ t2 = gcnew Test<String^>("hello");

   Console::WriteLine(t2); 

   Test<ArrayList^>^ t3 = gcnew Test<ArrayList^>(gcnew ArrayList);

   Console::WriteLine(t3); 

}



Listing Two



generic<class T> where T : IDisposable

ref class DisposableType

{

   T t;

public:

   DisposableType(T param) {t=param;}

   void Close()

   {

      t->Dispose();

   }

};





Listing Three



interface class IPrintable

{

   void Print();

};

ref class Printer

{

public:

   generic<class T> where T : IPrintable

   void PrintDoc(T doc)

   {

      doc->Print();

   }

};





Listing Four



// Old Syntax

String* Create(int i) __gc[]

{

   return new String __gc*[i];

}

// New Syntax

array<String^>^ create(int i)

{

   return gcnew array<String^>(i);

}





Listing Five



using namespace System;

using namespace stdcli::language;



double average([ParamArray] array<int>^ arr) 

{

   double av = 0.0;

   for (int j = 0 ; j < arr->Length ; j++)

      av += arr[j];

   return av / arr->Length;

}

void main() 

{

   Console::WriteLine("average is {0}", average(9, 3, 4, 2));

}





Listing Six



const int SIZE = 10;

array<int>^ a = gcnew array<int>(SIZE);

interior_ptr<int> p = &a[0];

for (int i = 0; i < SIZE; ++I, ++p)

   *p = i;





Listing Seven



String^ s = "hello";

interior_ptr<const Char> ptr = PtrToStringChars(s);

interior_ptr<Char> p = const_cast< interior_ptr<Char> >(ptr);

Console::WriteLine(s); // prints hello

*p = 'H';

Console::WriteLine(s); // prints Hello





Listing Eight 



// Illustrating the danger in interior_ptr<>

using namespace System;

using namespace stdcli::language;



ref class Bad

{

   __int64 x;

   __int64 y;

   String^ s;

public:

   Bad()

   {

      x = 1LL; y = 2LL; s = "test";

   }

   void KillMe()

   {

      Dump();

      interior_ptr<__int64> p = &x;

      *p = 3LL; // Change x

      Dump();

      p++;

      *p = 4LL; // Change y

      Dump();

      p++;

      *p = 5LL; // Change s

      // Dump will kill the process when it tries to access s 

      Dump();

   }

   void Dump()

   {

      Console::WriteLine("{0} {1} {2}", x, y, s);

   }

};

void main()

{

   Bad^ bad = gcnew Bad;

   bad->KillMe();

}









3



