Mehrdad Kamali
Mehrdad Kamali

Reputation: 87

How to pass a variable to a function without affecting it

i have something like this:

static void Main()
{
    int[] sqa = new int[2];
    sqa[0] = 1;
    sqa[1] = 2;
    func(sqa);
}

static void func(int[] sqa)
{
    sqa[0] = 0;
    sqa[1] = 1;
}

after i call func(), value change in `Main() function, too.

how can i prevent to do this and play with variables without changing them?

Upvotes: 0

Views: 90

Answers (2)

Shazi
Shazi

Reputation: 1569

This happens because the Array is a reference type. You can bypass this by creating a new Array and copying the values from the old Array to the new one.

static void Main()
{
    int[] sqa = new int[2];
    sqa[0] = 1;
    sqa[1] = 2;

    int[] sqa2 = new int[2];
    Array.Copy(sqa, sqa2, sqa.Length);

    func(sqa2);
}

static void func(int[] sqa)
{
    sqa[0] = 0;
    sqa[1] = 1;
}

Upvotes: 0

Dmitry
Dmitry

Reputation: 14059

Array in C# is a reference type, so it is always passed by reference.
You need to create a copy of input array in your func method:

static void func(int[] input)
{
    int[] sqa = (int[])input.Clone();

    sqa[0] = 0;
    sqa[1] = 1;
}

Upvotes: 4

Related Questions