sanchop22
sanchop22

Reputation: 2809

Array reference in classes in C#

i have an array and want to create two classes that contains the reference of this array. When i change value of an element in array, i want to see the change in classes. The reason why i want to do that is i have a array of something and i have many classes that should contain or reach this array. How can i do that?

In C, i put the pointer of the array in existing structs and solve the problem but how can i do that in C#? There is no array pointer afaik.

int CommonArray[2] = {1, 2};

struct
{
    int a;
    int *CommonArray;
}S1;

struct
{
    int b;
    int *CommonArray;
}S2;

S1.CommonArray = &CommonArray[0];
S2.CommonArray = &CommonArray[0];

Thank you.

Upvotes: 2

Views: 671

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500525

All arrays are reference types in C#, even if the element type of the array is a value type. So this will be fine:

public class Foo {
    private readonly int[] array;

    public Foo(int[] array) {
        this.array = array;
    }

    // Code which uses the array
}

// This is just a copy of Foo. You could also demonstrate this by
// creating two separate instances of Foo which happen to refer to the same array
public class Bar {
    private readonly int[] array;

    public Bar(int[] array) {
        this.array = array;
    }

    // Code which uses the array
}

...

int[] array = { 10, 20 };
Foo foo = new Foo(array);
Bar bar = new Bar(array);

// Any changes to the contents of array will be "seen" via the array
// references in foo and bar

Upvotes: 5

Related Questions