In a managed c++ class, should I be using a reference or an instance of a C# class that I've implemented in another library?
Consider this example:
// MyManagedClass.h
#pragma once
using namespace System::Collections::Generic;
using namespace My::Namespace::MyCSharpLib;
namespace My::Namespace::MyManagedLib
{
public ref class MyManagedClass
{
public:
MyCSharpClass myInst; // i have an instance!
MyCSharpClass ^myRef; // need to do gcnew
List<MyCSharpClass ^> listInst; // i have an instance!
List<MyCSharpClass ^> ^listRef; // need to do gcnew
};
}
And then the managed class is called from C# code:
// driver.cs
using My.Namespace.MyCSharpLib;
using My.Namespace.MyManagedLib;
public class Driver
{
private static void Main(string[] args)
{
MyManagedClass mmc = new MyManagedClass();
DoStuff(mmc);
}
}
My gut tells me I should be using myRef and listRef because that's what I'd be doing if this was implemented in C#. But why am I allowed to directly instantiate an instance of MyCSharpClass? What are the repercussions of doing this? If my class only ever has one collection of MyCSharpClass objects, is there harm is directly initializing the collection?