0

here is my for loop code,

private bool setspinerotate = false;
private bool setspinerotate2 = false;
private bool setspinerotate3 = false;
void clearall()
{
    bool[] checkjoint = {setspinerotate,setspinerotate2, setspinerotate3};
    for (int a = 0; a < checkjoint.Length; a++)
    {
        checkjoint[a] = true;
    }
} 

and I perform this function in another function, all the value is not turning to true. Why?

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • `checkjoint` knows *nothing* of where the values it was initialised with came from. There's no link between the array and the variables. – Damien_The_Unbeliever Dec 13 '21 at 09:28
  • 4
    `bool` is a value type. you change the _value_ in the array, not the value in the field. – René Vogt Dec 13 '21 at 09:28
  • 2
    Because booleans (in C#) are *value* types, meaning they don't get passed by reference, and instead are passed by value. Meaning the line `bool[] checkjoint = ...` is *copying* the values of the `setspinerotate` members, then you're modifying said copies instead of the original members – MindSwipe Dec 13 '21 at 09:29
  • @MindSwipe - This has nothing to do with value types and reference types. – Enigmativity Dec 13 '21 at 09:36
  • 1
    The same behaviour occurs for either a value type or a reference type. When we assign a value to the array it is replacing the existing value - irrespective of if it is a value type or a reference type. – Enigmativity Dec 13 '21 at 09:41
  • Also, I assume that the initial values in the question should be set to `true` otherwise the question itself doesn't really make sense. – Enigmativity Dec 13 '21 at 09:43
  • thank so how can I change the value type in for loop? @Enigmativity –  Dec 13 '21 at 09:44
  • @wildbeast - It doesn't matter if it's a value type or a reference type. If you want the original variable's value to change it's going to require something more special. The question is why can't you use the array to store your values? What's the reason you need to take those three values and put them in an array? There's an underlying design goal that you haven't made clear here. – Enigmativity Dec 13 '21 at 09:46

1 Answers1

3

The way that you would make this work is to only ever use the array. Don't create individual variables.

Do it like this:

private bool[] _setSpineRotates = new[] { false, false, false };

void ClearAll()
{
    for (int a = 0; a < _setSpineRotates.Length; a++)
    {
        _setSpineRotates[a] = true;
    }
}

NB: This has absolutely nothing to do with the difference between value-types versus reference-types. Both behave exactly the same in this circumstance.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172