0

I have some code that looks like this:

public static class Control
{
    public static Dictionary<PlayerIndex, GamePadState> gamePadState = new Dictionary<PlayerIndex,GamePadState>();
    public static Dictionary<PlayerIndex, GamePadState> oldGamePadState = new Dictionary<PlayerIndex, GamePadState>();

    public static void UpdateControlls()
    {
        gamePadState.Clear();
        foreach (PlayerIndex pIndex in pIndexArray)
        { gamePadState.Add(pIndex,GamePad.GetState(pIndex)); }
    }
}

As I looked through the code in Debug, when I called gamePadState.Add(...);, It also added to oldGamePadState, even though I never called oldGamePadState.Add(...);

sFuller
  • 1,305
  • 2
  • 14
  • 23

2 Answers2

4

Chances are very good that you have code elsewhere adding items to your dictionaries. I see that they are both public. Perhaps it would be good to make them private and only expose the dictionary methods through wrapper methods. Then you could set a breakpoint in those wrapper methods to find out what other code is accessing your dictionaries.

For example:

public static class Control
{
    //Change these to private
    private static Dictionary<PlayerIndex, GamePadState> gamePadState = new Dictionary<PlayerIndex,GamePadState>();
    private static Dictionary<PlayerIndex, GamePadState> oldGamePadState = new Dictionary<PlayerIndex, GamePadState>();

    public void AddOld(PlayerIndex index, GamePadState state)
    {
        oldGamePadState[index] = state;  // Set breakpoint here
        // When the breakpoint trips, look at the stack trace to find out
        // who is calling this method
    }

    public void AddNew(PlayerIndex index, GamePadState state)
    {
        gamePadState[index] = state;
    }
}

For details on why it's generally a good idea to use public properties (getters and setters) rather than plain-old public variables, see this stackoverflow answer.

Community
  • 1
  • 1
Phil
  • 6,561
  • 4
  • 44
  • 69
2

I suspect you've only actually got one dictionary, and you've got some code somewhere which is doing

Control.oldGamePadState = Control.gamePadState;

(or vice versa).

That doesn't copy the dictionary object from one variable to another - it copies the reference, so after that statement they'd both be referring to the same dictionary. If that's a surprise to you, read my article on reference types and value types.

As Phil says, you should consider making them private - and I'd also suggest you make the variables readonly. That won't make the dictionaries read-only - it will just prevent the variables from being reassigned.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • To verify whether this is the case, put a breakpoint on the `.Add()` line and evaluate Object.ReferenceEquals() (http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx) in the debugger to see whether the two dictionary references are the same. – Bevan Jan 29 '11 at 08:00