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

명관 송 21 Reputation points
2022-04-20T06:35:33.047+00:00

194545-image.png

C#
C#
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,307 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,296 Reputation points Microsoft Vendor
    2022-04-20T09:29:47.18+00:00

    @명관 송 , 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,
    Jack


    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) 56,931 Reputation points
    2022-04-20T15:19:23.06+00:00

    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