swap two strings in C#

In this article I will explain how we can swap two string in C#.
  • 13543


Swap the two string means to write a method that exchanges the strings in each other. In the example, two strings, str1 and str2, are initialized in Main and passed to the SwapStrings method as parameters modified by the ref keyword. The two strings are swapped inside the method and inside Main as well.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace swap


    class valswap


        public void swap(ref string p, ref string q)


            string temp;

            temp = p;

            p = q;

            q = temp;



    class Program


        static void Main(string[] args)


            valswap obj = new valswap();

            string str1 = "DotNet";

            string str2 = "Heaven";

            Console.WriteLine("x and y before call:   " + str1 + " " + str2);

            obj.swap(ref str1, ref str2);

            Console.WriteLine("x and y after call:   " + str1 + " " + str2);






The output of the program


© 2020 DotNetHeaven. All rights reserved.