Flip
Flip

Reputation: 23

Keep adding new value of the same variable to List

So can't seem to find any solution that fixes my problem: I get a string (lets say abcd) and I need to Rotate the characters once every time and store it into a list (or array), word_length! many times (! means Factorial). What I have so far works fine and does what I want (If I print out each value just before and after they get added to the list then it prints fine), except when I print out all the values in the list only at the end, all the values in the list are the same as the last assigned value for some reason I have no idea why. I've tried a lot of different things including assigning it to new variables each time, adding to an array instead of list etc. I'm pretty sure it's something to do with memory addresses or something. Can anyone please help. Here is my code:

static void Main(string[] args)
{     
    string word = "abcd";
    int word_length = word.Length;
    char[] word_arr = word.ToCharArray();
    List<char[]> list = new List<char[]>();
    list.Add(word_arr);
    while (list.Count < Factorial(word_length))
    {
        word_arr = RotateLetters(word_arr);
        list.Add(new_array);
    }
    list.ForEach(Console.WriteLine);
}


public static int Factorial(int n)
{
    int result = 1;
    while (n > 0)
        result *= (n--);
    return (result);
}

private static char[] RotateLetters(char[] word_arr)
{
    int i = 0, l = word_arr.Length - 1;
    char tmp = word_arr[0];
    while (i < l)
    {
        word_arr[i] = word_arr[i + 1];
        i++;
    }
    word_arr[l] = tmp;
    return (word_arr);
}

public static void Swap(ref char a, ref char b)
{
    if (a == b)
        return;
    char tmp = a;
    a = b;
    b = a;
}

Upvotes: 0

Views: 519

Answers (1)

Marker
Marker

Reputation: 977

You are adding a reference to the same array to your list. Each entry in the list references the same array in memory so when you modify the array, they change show up in every list item. You need to add a copy. Try:

list.Add((char[])word_array.Clone());

Upvotes: 3

Related Questions