简体   繁体   中英

When assigning a static array to a non-static array in C#, is it done by reference or value?

My question is one about C# language behaviour. I have code where I have a few static arrays with different values and a non-static field array which is being set to one of these arrays at a different time. My assumption is that if UpdateArrayToUse below was called, it would set it by reference, meaning that if LoadArrays was called again at a later time with the disk values having changed then the non-static field Options would have already changed. However, this isn't the behaviour I'm seeing. I'm curious to know if anybody has any insight into this.

    private static string[] StaticArray1;
    private static string[] StaticArray2;

    public static void LoadArrays()
    {
        //Loads arrays from disk, can be changed elsewhere
        StaticArray1 = LoadArray1();
        StaticArray2 = LoadArray2(); 
    }

    public void UpdateArrayToUse(int i)
    {
        if(i == 1){
            Options = StaticArray1;
            return;
        }

        Options = StaticArray2;
    }

    public string[] Options;

The code in LoadArray doesn't change any arrays. It assigns what the methods return, which apparently are new ones and you assign them to the variables. Therefore if you store a reference to a previous array somewhere it will still retain its value.

It would be different if the arrays were already created and you changed the values in them. Then what you expected to see would happen.

But we don't know exactly what the code inside those loading methods does. It could also use an internal array that isn't allocated again, in which case again it would be different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM