C# - Swap Two Numbers Using Pointer

Here, we will learn how to swap two numbers using the pointer in C#?
Submitted by Nidhi, on November 01, 2020 [Last updated : March 23, 2023]

Swapping two numbers

Here, we will swap the values of two integers using the pointer. To use pointer we need to write unsafe code, to compile unsafe code we need to allow unsafe code by clicking on properties in solution explorer and then "Allow Unsafe Code" from the Build tab.

C# program to swap two numbers using the pointer

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# - Swap Two Numbers Using 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.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.