0

I'm creating a guitar tab program.

You select notes (GameObject), type a chord name (string), then press a button to add the "Chord" to a list.

The Chord class is just a String and a list of GameObjects. I use currentChord to hold the current selection/name.

When I select a note, I add it to currentChord.selectedList.

When I type a name, I make it currentChord.name.

Chord currentChord;
List<Chord> allChords;

When I click a button, currentChord gets added to allChords (allChords.Add(currentChord)).

The problem is that it's instanced. So when I click to add a different selection/name, the selection of everything in the allChords.notes list changes...

Do I have to use the "new" keyword?

st4rdog
  • 93
  • 1
  • 6

2 Answers2

3

Yes, you have to use the new keyword.

You are adding the same instance to the list over and over, so you end up with a list of references to the same instance.

Create a new instance from the data in currentChord to add to the list, or add the instance in currentChord to the list and then create a new instance and assign to currentChord.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • If I copy the currentChord, will the string/List of Chord still be the instanced ones? So I have to create a new copy of the string/list vars and then set them as the Chord vars? – st4rdog May 27 '12 at 13:20
  • @st4rdog: If you copy the `currentChord` variable, you will just be copying the reference to the object, so you still only have one object. You have to create a new instance to get a copy. If the list of `GameObject` can change, you have to create a new list, not just copy the reference. If each `GameObject` can change, you have to create new instance of each, not just copy the reference to the new list. – Guffa May 27 '12 at 15:57
1

You may also want to consider the difference between the struct and class keywords which can be used to define Chord. Using struct will provide value-type behavior, where class will provide reference-type behavior.

For example, this is value-type behavior:

struct Chord
{
    public string Name;
}

...

Chord cMajor = new Chord;
cMajor.Name = "C Major";
Chord cMinor = cMajor; // Make a copy of the Chord instance
cMinor.Name = "C Minor";

Assert.That(cMajor.Name, Is.EqualTo("C Major")); // Assertion succeeds

This is reference-type behavior:

class Chord
{
    public string Name;
}

...

Chord cMajor = new Chord;
cMajor.Name = "C Major";
Chord cMinor = cMajor; // No copy of the Chord instance, just another reference
cMinor.Name = "C Minor";

Assert.That(cMajor.Name, Is.EqualTo("C Major")); // Assertion fails
Assert.That(cMajor.Name, Is.EqualTo("C Minor")); // Assertion succeeds

MSDN provides a nice description: http://msdn.microsoft.com/en-us/library/aa288471(v=vs.71).aspx

Josh Peterson
  • 2,299
  • 19
  • 21