473,770 Members | 5,977 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Collenct ion.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 2450
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_str eam;
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
1261
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, 6} Dim my_collection As New Collection my_collection.Add(array1, “Variable1”) my_collection Add(my_collection.Item(“Variable1”), “Variable2”) my_collection.Add(array2, “Variable3”)
5
2733
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 the appointment collection to populate the calendar control. The performance getting the XML data is fine, but loading the data into the collection is slow. My question/problem is should I be using the collection, a dataset, or something else to...
3
2823
by: PauloFor | last post by:
Hi have : struct A { public int val; } class OtherClass { private lis = new ArrayList();
3
20641
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 into other collection, which is a lengthy process. colBackupEmp = m_colEmp Above statement sets the reference.
5
1335
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 result represented by the following? clxn_Times(0) = clxn_Times(0).AddDays(-1) I can't find a way to edit an item in place. But not knowing very much
8
1833
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; namespace DeterminedGenericCollection { // I got tired of copy and pasting IDisposable
18
2210
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 documents that you could point me to help me control the GC, then that would be great also. The .Net GC does not cleanup memory of our service process unless it is forced to by another process that hogs memory. · GC Algorithm - This is an issue...
4
2774
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 fileName As String Public fileExtention As String Public filePath As String Public newName As String
5
3840
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 connectivity for basic operations and such. I've ran into a snag that I just can't think myself out of. Here's an example: I have an object for a Student called StudentRecord. It has properties such as name, grade, identification number, etc.
0
9592
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10231
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10005
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7416
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6679
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5313
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5452
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2817
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.