The source code to swap two numbers using pointers is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to swap two numbers using the pointer.
using System;
class UnsafeEx
{
static unsafe void Swap(int* X, int* Y)
{
int Z = 0;
Z = *X;
*X = *Y;
*Y = Z;
}
static unsafe void Main(string[] args)
{
int A = 10;
int B = 20;
Console.WriteLine("Before Swapping:");
Console.WriteLine("\tA: " + A);
Console.WriteLine("\tB: " + B);
Swap(&A, &B);
Console.WriteLine("After Swapping:");
Console.WriteLine("\tA: " + A);
Console.WriteLine("\tB: " + B);
}
}
Output:
Before Swapping:
A: 10
B: 20
After Swapping:
A: 20
B: 10
Press any key to continue . . .
Explanation:
In the above program, we created class UnsafeEx that contains two methods Swap() and Main(). Here, we used the unsafe keyword to define the unsafe method that can use pointers.
The Swap() is an unsafe static method, that took two pointer arguments, here we swapped the values of arguments using local variable Z.
In the Main() method, we created two variables A and B. Here, we printed the values of variables A and B before and after calling the Swap() method.
Program:
The source code to swap two numbers using pointers is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created class UnsafeEx that contains two methods Swap() and Main(). Here, we used the unsafe keyword to define the unsafe method that can use pointers.
The Swap() is an unsafe static method, that took two pointer arguments, here we swapped the values of arguments using local variable Z.
In the Main() method, we created two variables A and B. Here, we printed the values of variables A and B before and after calling the Swap() method.