0

I have a boolean that returns true or false after looking at some boolean arrays and ints.

if (CheckForRoute(VertWallAbove, HoriWallLeft, NewWallX, NewWallY, NewWallHor))

During this function the parameter that comes from HoriWallLeft has its value[0,0] set to true (Prior to this every value in the array is false and I have checked this is happening with breakpoints). immediately after exiting the function the value of HoriWallLeft[0,0] is true, I would've thought this would only happen if I am passing by ref.

Edit: Here is an example of what I mean

static void Main(string[] args)
{
    bool[] Test = new bool[] { false, false, false, false };
    ExampleFunction(Test);
    if(Test[0])
    {
        Console.WriteLine("A");
    }
    else
    {
    Console.WriteLine("B");
    }
    Console.ReadLine();
}
static bool ExampleFunction(bool[] TestArray)
{
    TestArray[0] = true;
    return true;
}

I would expect this to output B but it outputs A

Kronos
  • 126
  • 8
  • So, you're basically passing a pointer to an array of booleans. That's why you can modify individual elements. – rashmatash Dec 19 '19 at 13:06
  • arrays are reference-types. Doing anything on one reference is reflected in all other references to the same array-instance. – MakePeaceGreatAgain Dec 19 '19 at 13:07
  • Arrays are a reference type so the modification to TestArray[0] is actually applied to the array object to which it refers. – T_Bacon Dec 19 '19 at 13:07
  • @LittleSweetSeas - Your comment is misleading. The bool[] is not passed by reference unless the `ref` keyword is used. In the example code, it is passed by value. – Chris Dunaway Dec 19 '19 at 14:58

1 Answers1

2

This is correct, you are passing a reference to this array to the Function. There is no copy of the array created.

If you want a copy to be created, you could call

ExampleFunction(Test.ToArray());
Holger
  • 2,446
  • 1
  • 14
  • 13
  • Does this change if it is a multi-dimensional array? – Kronos Dec 19 '19 at 13:26
  • No, it would only change if you use ExampleFunction(bool b1, bool b2, bool b3). Bool is a value type, any array is a reference type. Your Test variable is a reference to an Array already; not the array itself. This is important to know when defining a readonly bool[] array. Here it's also only the reference that is readonly, not the values of the array. – Holger Dec 19 '19 at 13:45