364,033 Members | 4804 Browsing Online
Community for Developers & IT Professionals
Bytes IT Community

Problem instantiating custom class as array elements

kombu
P: 2
I've been working on an app to manage my iTunes collection, and have run into a bit of a snag. I've created two classes:

Column – Describes a column of information in the iTunes database
Track – Contains an array of Columns

When I instantiate a new Track object and attempt to build the array of Columns, each "new Column" statement overwrites the value of the previous array element.

I'm sure I'm missing something obvious – any ideas? (complete code is attached)

// this statement...
Track t = new Track();
// produces this output:
// array element 0 = Name
// array element 0 = Artist
// array element 1 = Artist

Expand|Select|Wrap|Line Numbers
  1.     public class Column
  2.         private static string _name;
  3.         private static string _datatype = "string";
  4.         private static Int16 _length = 0;
  5.         public Column(string name, string datatype, Int16 length)
  6.         {
  7.             _name = name;
  8.             _datatype = datatype;
  9.             if (datatype == "string" && length > 0)
  10.             {_length = length; }
  11.             else
  12.             {_length = 0;}
  13.         }
  14.  
  15. // Begin Track class
  16.     public class Track
  17.         private static Column[] _trackcolumns = new Column[2];
  18.         public static Column[] TrackColumns
  19.         {
  20.             get {return _trackcolumns;}
  21.             set { _trackcolumns = value; }
  22.         }
  23.         public Track()
  24.         {
  25.             _trackcolumns[0] = new Column("Name", "string", 30);
  26.             Console.WriteLine("array element 0 = {0}",_trackcolumns[0].Name);
  27.             _trackcolumns[1] = new Column("Artist", "string", 30);
  28.             Console.WriteLine("array element 0 = {0}", _trackcolumns[0].Name);
  29.             Console.WriteLine("array element 1 = {0}", _trackcolumns[1].Name);
  30.         }
  31.  
Attached Files
File Type: txt fullcode.txt (1.8 KB, 14 views)
Feb 7 '12 #1
Share this Question
Share on Google+
2 Replies


GaryTexmo
Expert 100+
P: 1,225
I'd imagine it's because your member variables are static. This means that there is only one instance of that object across all instances of that class.

Make your class members non-static and that should fix you up.
Feb 8 '12 #2

kombu
P: 2
That did the trick. Thanks, Gary!
Feb 8 '12 #3

Post your reply

Help answer this question



Didn't find the answer to your C# / C Sharp question?

You can also browse similar questions: C# / C Sharp