• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2239
  • Last Modified:

How to implement call-by-reference in C# ?

plz look at the following code.

class Test
{
     public static void swap(int &a,int &b)
     {
          int c=a; a=b; b=c;
     }
     public static void Main()
     {
          int x=10,y=20;
          swap(x,y);
          System.Console.WriteLine("x={0} and y={1}",x,y);
     }
};

   It is not working. I tried the same
swap function using pointers too as follows

     public static void swap(int *p,int *q)
     {
          int c=*p; *p=*q; *q=c;
     }
0
balakiran_bs
Asked:
balakiran_bs
1 Solution
 
LagiCommented:
You should use

void swap(ref int a, ref int b)
{
  int c = a;
  a = b;
  b = c;
}

static void main()
{
  int a = 10;
  int b = 20;
  swap(ref a, ref b);
}
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now