[Gtk-sharp-list] is this legal in C#
George Farris
george@gmsys.com
27 Feb 2003 21:03:41 -0800
Of course, what an idiot I am. Ya know sometime you just can't see the
forest for the trees.
Thanks.
On Thu, 2003-02-27 at 21:08, Ian MacLean wrote:
> 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
> >
--
George Farris <george@gmsys.com>