473,796 Members | 2,640 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Puzzling Collections

I attach the following code and output. I Add an object to a
Collection. I modified a property of the object. The item in the
Collection gets modifed also. Can you help me determine where I have
gone wrong. Thanks.
public class Shape
{
protected Size _size;
protected Point _location;

public Size Size
{
get{return _size;}
set{_size=value ;}
}

public Point Location
{
get{return _location;}
set{_location=v alue;}
}

public Shape()
{ }
}
public class Rect : Shape
{
public Rect(Point loc, Size size) : base()
{
_size = size;
_location = loc;
}
}

// For second example
public class ShapeCollection : CollectionBase
{
public ShapeCollection () : base()
{ }

public void Add(Shape s)
{ this.List.Add(s ); }

public Shape this[int index]
{
get
{ return (Shape)List[index]; }

set
{ List[index]=value; }
}
}

public class RectanglesColle ction : CollectionBase
{
public RectanglesColle ction() : base()
{ }
public void Add(Rectangle r)
{ this.List.Add(r ); }

public Rectangle this[int index]
{
get
{ return (Rectangle)List[index]; }
set
{ List[index]=value; }
}
}

public void test()
{
ShapeCollection shapes = new ShapeCollection ();
Rect rect = new Rect (new Point(0,0), new Size(50,50));
shapes.Add(rect );
Debug.WriteLine ("1st item: " + shapes[0].Location.ToStr ing());

rect.Location=n ew Point(2,2); //Change .Location property
Debug.WriteLine ("1st item again: " +
shapes[0].Location.ToStr ing() + " Why?!");

shapes.Add(rect );

foreach (Shape sh in shapes) Debug.WriteLine
(sh.Location.To String());

Debug.WriteLine ("============= =");

RectanglesColle ction rectanglesColle ction = new
RectanglesColle ction();
Rectangle r = new Rectangle(new Point(0,0), new Size(100,50));
rectanglesColle ction.Add(r);
r.Location = new Point(5,5); // change the .Location property
Debug.WriteLine ("List item after r modified: " +
rectanglesColle ction[0].ToString());
rectanglesColle ction.Add(r);
foreach (Rectangle rx in rectanglesColle ction)
Debug.WriteLine (rx.ToString()) ;
}
Output:
-------

1st item: {X=0,Y=0}
1st item again: {X=2,Y=2} Why?!
{X=2,Y=2}
{X=2,Y=2}
==============
List item after r modified: {X=0,Y=0,Width= 100,Height=50}
{X=0,Y=0,Width= 100,Height=50}
{X=5,Y=5,Width= 100,Height=50}

Nov 17 '05 #1
9 1260
Hi Sue & Bill,
you have done nothing wrong this is the expected behaviour that you should
get. Basically in .Net there are two main types of variables: Value and
References. Value variables get copied when assigned i.e.

int i = 3;
int j = i;
j += 1;

--> now i is still 3 and j is 4

This is because value types get copied when you pass them round - I think
this is what you were expecting to happen in your code below.

However, the other type, reference types do not get copied. This applies to
all objects, which are reference types (strings behave a little bit
differently, but we will not go into that here). In this case your variable
does not contain the actual data but really just a reference to the object
i.e.

MyClass c1 = new MyClass();
c1.Name = "c1";
MyClass c2 = c1;
c2.Name = "c2"

--> Now both c1.Name and c2.Name will return "c2"

c1,c2 are referencing the same instance of the MyClass object

c1 ------
\
---------------- MyClass Instance
c2 ------/
When you add an item to a collection you are really just passing a reference
to the object, not the actual object itself, so if you modify the object's
state in any way then when you access the reference in the collection which
is pointing to the modified object it will obviously show the modified state.
If you do not want the item in the collection to get modified you should
create a clone of the object before you put it intto the collection - this is
a duplicate copy of the object, look into the ICloneable interface.
Hope that helps
Mark R Dawson

"Sue & Bill" wrote:
I attach the following code and output. I Add an object to a
Collection. I modified a property of the object. The item in the
Collection gets modifed also. Can you help me determine where I have
gone wrong. Thanks.
public class Shape
{
protected Size _size;
protected Point _location;

public Size Size
{
get{return _size;}
set{_size=value ;}
}

public Point Location
{
get{return _location;}
set{_location=v alue;}
}

public Shape()
{ }
}
public class Rect : Shape
{
public Rect(Point loc, Size size) : base()
{
_size = size;
_location = loc;
}
}

// For second example
public class ShapeCollection : CollectionBase
{
public ShapeCollection () : base()
{ }

public void Add(Shape s)
{ this.List.Add(s ); }

public Shape this[int index]
{
get
{ return (Shape)List[index]; }

set
{ List[index]=value; }
}
}

public class RectanglesColle ction : CollectionBase
{
public RectanglesColle ction() : base()
{ }
public void Add(Rectangle r)
{ this.List.Add(r ); }

public Rectangle this[int index]
{
get
{ return (Rectangle)List[index]; }
set
{ List[index]=value; }
}
}

public void test()
{
ShapeCollection shapes = new ShapeCollection ();
Rect rect = new Rect (new Point(0,0), new Size(50,50));
shapes.Add(rect );
Debug.WriteLine ("1st item: " + shapes[0].Location.ToStr ing());

rect.Location=n ew Point(2,2); //Change .Location property
Debug.WriteLine ("1st item again: " +
shapes[0].Location.ToStr ing() + " Why?!");

shapes.Add(rect );

foreach (Shape sh in shapes) Debug.WriteLine
(sh.Location.To String());

Debug.WriteLine ("============= =");

RectanglesColle ction rectanglesColle ction = new
RectanglesColle ction();
Rectangle r = new Rectangle(new Point(0,0), new Size(100,50));
rectanglesColle ction.Add(r);
r.Location = new Point(5,5); // change the .Location property
Debug.WriteLine ("List item after r modified: " +
rectanglesColle ction[0].ToString());
rectanglesColle ction.Add(r);
foreach (Rectangle rx in rectanglesColle ction)
Debug.WriteLine (rx.ToString()) ;
}
Output:
-------

1st item: {X=0,Y=0}
1st item again: {X=2,Y=2} Why?!
{X=2,Y=2}
{X=2,Y=2}
==============
List item after r modified: {X=0,Y=0,Width= 100,Height=50}
{X=0,Y=0,Width= 100,Height=50}
{X=5,Y=5,Width= 100,Height=50}

Nov 17 '05 #2
Mark, thanks for the explanation.

Yes, I kow about value and reference types. That's why I included a
second example. The second example is also Adding objects to a
Collection but the result is different. Do you mind taking another
look.

(Errata: the "// For second example" remark should be one block down.)

Anyway, the total documentation on IList.Add says "When implemented by
a class, adds an item to the IList." It does not give the slightest
hint whether an item is Added by reference or by copying.

Thanks in advance.

Nov 17 '05 #3
Hi Sue & Bill,
ah - sorry just woken up and answered before eating my weetabix, always a
bad thing to do, now I have some sugar pumping around my veins I see more
clearly, I did not notice you were using Rect and Rectangle in your examples.

In your first example you add instances of your Rect class to the collection:

ShapeCollection shapes = new ShapeCollection ();
Rect rect = new Rect (new Point(0,0), new Size(50,50));
shapes.Add(rect );
Console.WriteLi ne("1st item: " + shapes[0].Location.ToStr ing());

rect.Location=n ew Point(2,2); //Change .Location property
Console.WriteLi ne("1st item again: " +shapes[0].Location.ToStr ing() + "
Why?!");
shapes.Add(rect );

foreach (Shape sh in shapes)
Console.WriteLi ne(sh.Location. ToString());
Your rect class is passed as a refence into the collection, so you modify
the Location property to be 2,2 therefore the reference in the collection and
your rect variable are still pointing to the same object that is why you are
seeing:
{X=2,Y=2}
{X=2,Y=2}
in your output.

In your second example, you are adding Rectangle structures into the
collection. This type is a struct not a class, structs are passed by value
into the collection, i.e. a copy is created of the object when you add it to
the collection. So after you have added a COPY of the rectangle into the
collection and say:

r.Location = new Point(5,5);

you are changing the location of the r variable instance but not the COPY of
the rectangle which is now in the collection.

An easy way to tell if a class is a value type or reference type is to look
at the .Net documentation and see if the object inherits from
System.ValueTyp e if so then it will have ValueType semantics, such as the
Rectangle class does.

You might want to look into Boxing and Unboxing as well to help you more in
this topic.

Hope that helps
Mark R Dawson.

"Sue & Bill" wrote:
Mark, thanks for the explanation.

Yes, I kow about value and reference types. That's why I included a
second example. The second example is also Adding objects to a
Collection but the result is different. Do you mind taking another
look.

(Errata: the "// For second example" remark should be one block down.)

Anyway, the total documentation on IList.Add says "When implemented by
a class, adds an item to the IList." It does not give the slightest
hint whether an item is Added by reference or by copying.

Thanks in advance.

Nov 17 '05 #4
When you return a shape, this is a reference type so you actually return a reference to the object in the cvollection and this gets modified. When you return a Rectangle this is a value type and so a copy of the one in the collection is returned

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Mark, thanks for the explanation.

Yes, I kow about value and reference types. That's why I included a
second example. The second example is also Adding objects to a
Collection but the result is different. Do you mind taking another
look.

(Errata: the "// For second example" remark should be one block down.)

Anyway, the total documentation on IList.Add says "When implemented by
a class, adds an item to the IList." It does not give the slightest
hint whether an item is Added by reference or by copying.

Thanks in advance.
Nov 17 '05 #5
Mark, thank you very much for the explanation. I get it now. Didn't
realize the subtle differences. Still new to C#.

Nov 17 '05 #6
Thanks to all.

I just realized that my original problem is still not solved. I want
to create a list and plug objects in them. I don't want to keep a copy
of each object outside the list, because they will be created at run
time and I won't know how to name them. Any suggestions for the most
appropriate method?

Thanks.

Nov 17 '05 #7
Sue & Bill <su**********@g mail.com> wrote:
I attach the following code and output. I Add an object to a
Collection. I modified a property of the object. The item in the
Collection gets modifed also.


You don't add an object to the collection - you add a *reference* to
the collection.

The following web pages try to help explain reference types (and how
they're different to value types):

http://www.pobox.com/~skeet/csharp/memory.html
http://www.pobox.com/~skeet/csharp/parameters.html

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
Sue & Bill <su**********@g mail.com> wrote:
Thanks to all.
Glad the others have sorted you out with the earlier problem - sorry
about the reply I just posted to your original message. I should have
read the whole thread first :)
I just realized that my original problem is still not solved. I want
to create a list and plug objects in them. I don't want to keep a copy
of each object outside the list, because they will be created at run
time and I won't know how to name them. Any suggestions for the most
appropriate method?


Just add the reference to the list, and it'll be fine - there's no
concept of the object itself "belonging" to the list or to outside the
list - just the fact that the list has a reference to the object will
stop it from being garbage collected, if that's what you were worried
about. (If the list itself is eligible for garbage collection, the
objects referred to by the list is also eligible if there are no other
references to them.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #9
You may want a type based class factory.

http://www.geocities.com/Jeff_Louie/OOP/oop18.htm

Regards,
Jeff
I just realized that my original problem is still not solved. I want

to create a list and plug objects in them. I don't want to keep a copy
of each object outside the list, because they will be created at run
time and I won't know how to name them. Any suggestions for the most
appropriate method?<

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #10

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

Similar topics

2
2065
by: njp | last post by:
BlankHi, How do I create a tightly coupled Object 1 such that when I update it in one collection, it is simultaneously and automatically updated in other collections? The collections are defined at the module level for the entire project to access as well as collections defined within different objects. Currently, I'm updating Object 1 manually in all the different collections but there surely must be a better way. Thanks! NJ
1
2591
by: Tim T. | last post by:
I'm currently working on a report to forecast production for finished goods. The user can select one or more items to forecast. In addition, they may select one or more warehouses to view breakdowns for as well as one or more customers. Now, the report iterates through the selected items in the finished good listbox. For each item that it comes across, it calls 4 routines to gather various totals. Each routine will gather a total for...
5
4233
by: Simon | last post by:
Hi all, I am writing a windows application using vb.net on the 1.1 framework. We have in the application, some strongly typed collections that have been written as classes that do not inherit from collection base, but use an internal collection, to hold the objects and then implement IEnumerator, see example below,
4
8192
by: nhmark64 | last post by:
Hi, Does System.Collections.Generic.Queue not have a Synchronized method because it is already in effect synchronized, or is the Synchronized functionality missing from System.Collections.Generic.Queue? Putting it another way can I safely replace a System.Collections.Queue.Synchronized(myUnSynchronizedQueue) with a System.Collections.Generic.Queue while porting a working 2003 project? Thanks,
4
2224
by: Adam Clauss | last post by:
I ran into a problem a while back when attempting to convert existing .NET 1.1 based code to .NET 2.0 using Generic collections rather than Hashtable, ArrayList, etc. I ran into an issue because the old code allowed me to do what basically was the following assignment: class SomeClass { private Queue q; SomeClass(Queue q)
5
2637
by: WebSnozz | last post by:
Some collections are such that efficient search algorithms work on them such as binary search if the collection is a type which is sorted. I'm wondering how LINQ searches these collections and if it takes advantage of the fact that some collections are sorted? We were speculating that the standard .net 2.0 collections might implement the IQueryable interface for those collections where there are more efficient search algorithms.
2
7364
by: Fred Heida | last post by:
Hi, i'm trying to (using managed C++) implment the IEnumerable<Tinterface on my class.. but have a problem with the 2 GetEnumerator method required.... what i have done is... generic<typename T> public ref class SetOfProxy : public System::Collections::Generic::IEnumerable<T>
4
3995
by: Sid Price | last post by:
Hello, I have a class of objects (Device) that are managed by another object (Devices) with a collection class (DeviceCollection) inherited from Collections.Hashtable. Each of the Device objects can raise an event and I need the managing class (Devices) to be able to catch these events. Public Class Device Public Event StatusChange()
5
4191
by: Michi Henning | last post by:
I can pass a generic collection as ICollection<Tjust fine: static void flatCollection(ICollection<intc) {} // ... List<intl = new List<int>(); flatCollection(l); // Works fine Now I want to pass nested collections generically:
0
9673
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9525
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10452
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
10169
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,...
0
10003
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6785
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();...
1
4115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
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.