M
muchan
I'm a C++ programmer now poking into C#.
I wanted to write a snippet of code, equivalent of
//--- C++ code ---------------
#include <string>
#include <vector>
class obj { // a POD class
public:
std::string s;
//... other data omitted
};
std::vector<obj> v;
obj o; // a buffer on the stack
o.s = "aaa";
v.push_back();
o.s = "bbb";
v.push_back();
//----------------------------
Using System.Collenction.Generic I could write a quite similar code,
//--- C# code that failed -----
class obj {
public String s;
}
Collection<obj> col;
obj o = new obj();
o.s = "aaa";
col.Add(o);
o.s = "bbb"; // <--- here the col[0].s is also changes as "aaa"
col.Add(o);
//------------------------------
I see that the Add is adding a reference of o, so the values of o are
not copied to the collection.
Adding a Clone() function to the POD object like:
//---- C# clode that worked ---
class obj {
public String s;
public Obj Clone() // return a clone of POD object
{
Obj o = new Obj();
o.s = this.s;
return o;
}
}
Collection<obj> col;
obj o = new obj();
o.s = "aaa";
col.Add(o.Clone());
o.s = "bbb";
col.Add(o.Clone());
//-------------------------------
This seems to work, and does the same thing like C++'s code.
But writing Clone function for each data member isn't very attractive,
esp. when the structure becoming more complecated.
Isn't there a simpler syntax to do the same copy/clone things
at Collection.Add()?
muchan
I wanted to write a snippet of code, equivalent of
//--- C++ code ---------------
#include <string>
#include <vector>
class obj { // a POD class
public:
std::string s;
//... other data omitted
};
std::vector<obj> v;
obj o; // a buffer on the stack
o.s = "aaa";
v.push_back();
o.s = "bbb";
v.push_back();
//----------------------------
Using System.Collenction.Generic I could write a quite similar code,
//--- C# code that failed -----
class obj {
public String s;
}
Collection<obj> col;
obj o = new obj();
o.s = "aaa";
col.Add(o);
o.s = "bbb"; // <--- here the col[0].s is also changes as "aaa"
col.Add(o);
//------------------------------
I see that the Add is adding a reference of o, so the values of o are
not copied to the collection.
Adding a Clone() function to the POD object like:
//---- C# clode that worked ---
class obj {
public String s;
public Obj Clone() // return a clone of POD object
{
Obj o = new Obj();
o.s = this.s;
return o;
}
}
Collection<obj> col;
obj o = new obj();
o.s = "aaa";
col.Add(o.Clone());
o.s = "bbb";
col.Add(o.Clone());
//-------------------------------
This seems to work, and does the same thing like C++'s code.
But writing Clone function for each data member isn't very attractive,
esp. when the structure becoming more complecated.
Isn't there a simpler syntax to do the same copy/clone things
at Collection.Add()?
muchan