Reputation: 285
i m trying to make a project that requires the use of list.i cant seem to get it to work. following is my code:
ref class MyClass2
{
public:
int x;
String^ str;
}
List<MyClass2> lst =gcnew List<MyClass2>(); //here is the error
I am working in visual studio 2008.
Upvotes: 2
Views: 80
Reputation: 28563
You need this (note the three total ^
used):
List<MyClass2^>^ lst =gcnew List<MyClass2^>();
This is because MyClass2
is a reference type and can only be used with MyClass2^
and allocated with gcnew
(just like List
).
Thus you have a reference to a List
that can contain references to MyClass2
.
Then, to add items:
MyClass2^ mc = gcnew MyClass2();
mc->x = 2; //Set values
lst->Add(mc);
Upvotes: 1
Reputation: 61339
gcnew
returns a reference. You can't just assign it to an object. Also, you are storing references, not objects. Thus, just do this:
List<MyClass2^>^ lst = gcnew List<MyClass2^>(); //note what I'm assigning to
Similarly, with standard new
you have to use pointers.
Upvotes: 0