473,395 Members | 1,437 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Collection.Add() as Copy of the data, not Reference to the the data


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

Feb 9 '06 #1
3 2427
Vadym Stetsyak wrote:

AFAIR in C++ type has to have copy constructor, right? Isn't it equivalent to Clone?

m> Collection<obj> col;
m> obj o = new obj();
m> o.s = "aaa";
m> col.Add(o.Clone());
m> o.s = "bbb";
m> col.Add(o.Clone());
m> //-------------------------------

You can instantiate different objects, IMO it will be more clear that these objects are different
e.g.
obj o = new obj();
o.s = "aaa";
col.Add(o);
o = new obj();
o.s.= "bbb";
col.Add(o);

I thought this version...
but I encountered this problem while reading the data streams in a loop,
and filling the object inside the loop and at some point adding to the
Collection. if I used

obj o = new obj(); // a first instance
while (...) {
....
o.s = "something_from_the_source_stream;
continue;

....
if (some_condition_met) {
obj clone = new obj();
cloned = o; // <-- this is again the reference! ;(
col.Add(clone); // <-- so this is not good...
continue;
}
}

so before filling the data, the new should be called, like

if (some_condition_met) {
col.Add(o); // <-- here add the reference of preciously filled obj
o = new obj(); // <-- and prepare the new buffer to fill the data
continue;
}

This might work, but as a C++ programmer, I feel very very bad to loosing
the previous o at asigning the new obj()... My head is not GCed yet.
(and when I'll feel this normal, I wonder if I won't do it on C++! horror!)
Another way is that you can clone type in the Add method, however to do it, you have to
write your own collection class.

writing my own collection class doesn't sound good idea, tho...

Isn't there a simple way to creat a temporary buffer object on the stack?
(Otherwise C# is not so similar to the C/C++, indeed...)
--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com


Thanks for the suggestion.

muchan
Feb 9 '06 #2
Hello, muchan!

have a look at stackalloc keyword, but beware this is unsafe mode.

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
Feb 9 '06 #3
Vadym Stetsyak wrote:
Hello, muchan!

have a look at stackalloc keyword, but beware this is unsafe mode.


It's interesting, that it's possible but declared as "unsafe"...
In this wording, all my C++ programing was in unsafe mode. :)

Everybody now a days seems to see pointer as an evil, but in C++,
often declaring a alias (reference) of the content of pointer,
it can be used just like normal variable.

If I could do something like this:

unsafe void func()
{
Obj *op = stackalloc Obj;
Obj &o = *op; // o as alias to the pointee of op

// ... using o as the stack allocated object ...

} // at the end of scope it disappears from stack

This is equivalent to my C++ way of writing auto variable of the
function scope... In C++, using stack allocated variables feels
safer than memory managiment with calling "new".
But GC way looks like "just calling new, and don't worry about it".

Thank you very much.
muchan
Feb 10 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Emilia | last post by:
Dear colleagues, I have a collection which stores arrays of numbers. I do the following to fill the elements of the collection: Dim array1() As Integer = {1, 2, 3} Dim array2() As Integer = {4,...
5
by: Kurt Bauer | last post by:
I have an ASP group calendar application which pulls calendar data from Exchange via webdav into an XML string. I then loop the XML nodes to populate a collection of appointments. Finally I use...
3
by: PauloFor | last post by:
Hi have : struct A { public int val; } class OtherClass { private lis = new ArrayList();
3
by: Sakharam Phapale | last post by:
Hi All, eg. "Array.Copy" method used to copy array elements. Is there any method to copy collection objects data, except iterating through original collection and then filling each element...
5
by: Jeff Stewart | last post by:
Let's say I create a collection of DateTime objects like so: Dim clxn_Times As Collection = New Collection() Let's go on to say I add 3 elements to the collection. How do I pull off the...
8
by: JAL | last post by:
Here is my first attempt at a deterministic collection using Generics, apologies for C#. I will try to convert to C++/cli. using System; using System.Collections.Generic; using System.Text; ...
18
by: Larry Herbinaux | last post by:
I'm having issues with garbage collection with my long-standing service process. If you could review and point me in the right direction it would be of great help. If there are any helpful...
4
by: Kyote | last post by:
I'm trying to persist a list of filenames. I've made a custom collection and a FileName class: 'Class to hold file name information Public Class FileNames Public fullName As String Public...
5
by: David Longnecker | last post by:
I'm working to create a base framework for our organization for web and client-side applications. The framework interfaces with several of our systems and provides the business and data layer...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.