[Gtk-sharp-list] is this legal in C#

Ian MacLean ianm@ActiveState.com
Fri, 28 Feb 2003 14:08:03 +0900


George,

This is because you are repeatedly setting values on the same instance. 
So every element of the array is a reference to the same object c. Try this:

	Phonebook[] pbooks = null; 						
  	pbooks = new Phonebook[3]; 			  	
  	for (int i = 0; i < 3; i++  )
  	{
  		// Create a new instance in each loop iteration
		Phonebook c = new Phonebook();
		c.Name = "name"+i.ToString());
  		c.Type = "type"+i.ToString());
  		c.Path = "path"+i.ToString());
  		pbooks[i] = c;
  	}
Ian
> Is this legal to make an array of a class?  I think so but it doesn't
> work.  Mono 0.20 on Linux.
> 
> public class Phonebook
> {
> 	public string Name;
> 	public string Path;
> 	public string Type;
> }
> 	
> public class Phonetools
> {
> 	Phonebook[] pbooks = null;
> 						
> 	pbooks = new Phonebook[3];
> 			
> 
> 	Phonebook c = new Phonebook();
> 	for (int i = 0; i < 3; i++  )
> 	{
> 		c.Name = "name"+i.ToString());
> 		c.Type = "type"+i.ToString());
> 		c.Path = "path"+i.ToString());
> 		pbooks[i] = c;
> 	}
> 
> 	foreach (Phonebook x in pbooks)
> 		Console.WriteLine(x.Name);
> }
> 			
> 
> The foreach line always gives me the same value which is the last one
> assigned to c.Name, like so:
> name 2
> name 2
> name 2
> 
> I was hoping it would give:
> name 0
> name 1
> name 2
>