C# program to swap two numbers using the pointer

Here, we are going to learn how to swap two numbers using the pointer in C#?
Submitted by Nidhi, on November 01, 2020

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.


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);


Before Swapping:
        A: 10
        B: 20
After Swapping:
        A: 20
        B: 10
Press any key to continue . . .


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!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.