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

Charles Iliya Krempeaux charles@reptile.ca
27 Feb 2003 21:17:19 -0800


Hello,

Objects are passed by reference.  Not by value.

So... pbooks[0], pbooks[1], and pbooks[2] all reference
"c".  In other words, they all point to the same object.

You probably want to something like this instead...


public class Phonebook
{
        public string Name;
        public string Path;
        public string Type;
}
        
public class Phonetools
{
        Phonebook[] pbooks = null;
                                                
        pbooks = new Phonebook[3];
                        
        for (int i = 0; i < 3; i++  )
        {
                pbooks[i] = new Phonebook();

                pbooks[i].Name = "name"+i.ToString());
                pbooks[i].Type = "type"+i.ToString());
                pbooks[i].Path = "path"+i.ToString());
        }

        foreach (Phonebook x in pbooks)
                Console.WriteLine(x.Name);
}


That should work.


See ya

On Thu, 2003-02-27 at 20:33, George Farris wrote:
> 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
-- 
     Charles Iliya Krempeaux, BSc
     charles@reptile.ca

________________________________________________________________________
 Reptile Consulting & Services    604-REPTILE    http://www.reptile.ca/