Value type and reference type problem

前端 未结 7 1623
花落未央
花落未央 2021-01-21 04:59

Hi I\'m trying to do a simple swap of two objects.My code is

void Main()
{
  object First = 5;
  object Second = 10;

  Swap(First, Second);
  //If I display res         


        
7条回答
  •  感动是毒
    2021-01-21 05:22

    You're passing the reference to the objects by value (pass by value is the default in C#).

    Instead, you need to pass the objects to the function by reference (using the ref keyword).

    private static void Swap(ref object first, ref object second)
    {
        object temp = first;
        first = second;
        second = temp;
    }
    
    void Main()
    {
        object first = 5;
        object second = 10;
    
        Swap(ref first, ref second);
    }
    

    Of course, if you're using C# 2.0 or later, you would do better to define a generic version of this function that can accept parameters of any type, rather than the object type. For example:

    private static void Swap(ref T first, ref T second)
    {
        T temp;
        temp = first;
        first = second;
        second = temp;
    }
    

    Then you could also declare the variables with their proper type, int.

提交回复
热议问题