Problem instantiating custom class as array elements

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kombu
    New Member
    • Feb 2012
    • 2

    Problem instantiating custom class as array elements

    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

    Code:
        public class Column
            private static string _name;
            private static string _datatype = "string";
            private static Int16 _length = 0;
            public Column(string name, string datatype, Int16 length)
            {
                _name = name;
                _datatype = datatype;
                if (datatype == "string" && length > 0)
                {_length = length; }
                else
                {_length = 0;}
            }
    
    // Begin Track class
        public class Track
            private static Column[] _trackcolumns = new Column[2];
            public static Column[] TrackColumns
            {
                get {return _trackcolumns;}
                set { _trackcolumns = value; }
            }
            public Track()
            {
                _trackcolumns[0] = new Column("Name", "string", 30);
                Console.WriteLine("array element 0 = {0}",_trackcolumns[0].Name);
                _trackcolumns[1] = new Column("Artist", "string", 30);
                Console.WriteLine("array element 0 = {0}", _trackcolumns[0].Name);
                Console.WriteLine("array element 1 = {0}", _trackcolumns[1].Name);
            }
    Attached Files
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    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.

    Comment

    • kombu
      New Member
      • Feb 2012
      • 2

      #3
      That did the trick. Thanks, Gary!

      Comment

      Working...