Re: How to swap two variable later?

From: Marcin Grzębski (mgrzebski_at_taxussi.no.com.spam.pl)
Date: 10/01/04


Date: Fri, 01 Oct 2004 14:49:12 +0200

Hi,

It looks impossible to do this in "safe" code,
but there is a simple trick:

<changes in your code>

  using System;
  using System.Collections;

  namespace Test
  {
     public class MyClass
     {
       public static void Main()
       {
          string[] mainA=new string[1];
        string[] mainB=new string[1];
          mainA[0]="A";
          mainB[0]="B";
          
          Swap swapCommand = new Swap(mainA, mainB);
          Console.WriteLine(mainA[0]);// Print "A"
// i fix your bug here
          Console.WriteLine(mainB[0]);// Print "B"
          
          swapCommand.Do(); // Swap take plase here...
          Console.WriteLine(mainA[0]);//want to Print "B" not A
// i fix your bug here
          Console.WriteLine(mainB[0]);//wnat to print "A" not B
       }
     }
          
     public class Swap
     {
        string[] _A;
        string[] _B;
          
        public Swap(string[] a, string[] b)
        {
          _A = a;
          _B = b;
        }
          
        public void Do()
        {
          string temp;
          temp = _A[0];
          
          _A[0] = _B[0];
          _B[0] = temp;
        }
     }
  }

HTH

Marcin



Relevant Pages


Loading