Why can't the elements of the list be ref?

명관 송 21 Reputation points


An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,633 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,496 Reputation points Microsoft Vendor

    @명관 송 , based on my test, I reproduced your problem.

    According to the Microsoft doc ref said, An argument that is passed to a ref or in parameter must be initialized before it is passed.

    Therfore, we could use the following code to initialize the argument.

      public static void GetSuffleList<T>(ref List<T>_list)  
                for (int i = 0; i < _list.Count; i++)  
                    Random random = new Random();  
                    int rnd = random.Next(0, i);  
                    T t1= _list[i];  
                    T t2= _list[rnd];  
                    Swap(ref t1 ,ref t2);  

    Hope this coudl help you.

    Best Regards,

    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,416 Reputation points

    Pass by ref means you pass the address of the variable, rather than the address of the value. But indexing into an array is really method that return a value, not a variable.

    As suggested above you could copy the indexed values to variable, but calling your swap would swap the values in variables not the list.

    0 comments No comments