How to Swap Variable Values Without the Use of Temporary Variable in C# (2024)

  1. Use Tuple Assignment in C#
  2. Use the + Operator to Get Around the Temporary Variable Used in C#
  3. Use a Function to Swap Values Rather Than Explicit Implementation to Hide Temporary Variable Use in C#
  4. How to Use the XOR Operator to Swap in C#
How to Swap Variable Values Without the Use of Temporary Variable in C# (1)

So, let’s say you are writing a code now and want to exchange variable values. You will probably do something like this:

using System;public class Program { public static void Main(string[] args) { var val_one = 123; var val_two = 234; var val_swap = val_one; val_one = val_two; val_two = val_swap; Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two); }}

Now here, you first create a temporary variable called val_swap, then you copy the val_one value to it so that after the val_one value is modified, you can easily copy the original val_one value back into val_two by assigning the value from val_swap into it.

Today, we will be looking at eliminating the use of this temporary variable and performing such an exchange without any other allocations.

Use Tuple Assignment in C#

A very simple method that you can now utilize is to use a TUPLE assignment as follows.

(val_one, val_two) = (val_two, val_one);Console.WriteLine("The value after swapping from the tuple method is: " + val_one + " and -> " + val_two);

Complete Code:

using System;public class Program { public static void Main(string[] args) { var val_one = 123; var val_two = 234; (val_one, val_two) = (val_two, val_one); Console.WriteLine("The value after swapping from the tuple method is: " + val_one + " and -> " + val_two); }}

Output:

The value after swapping from the tuple method is: 234 and -> 123

This method has also been used in Python; however, not subjected to tuples.

However, sometimes you have to use tricks to get what you want. Let’s look at an example below.

Use the + Operator to Get Around the Temporary Variable Used in C#

Let’s say we have two numbers; 7 and 9. The first variable has the value 7, and the second variable has the value 9.

If we add 9 to 7, we’ll get 16. Let’s assign 16 to the first variable now.

To put 9 as the value of the first variable, you have to deduct the value of 9 from the second variable, which would become 15-9 = 7; use this value and subtract it from 15 in the first variable to now get the value 9.

val_one += val_two;val_two = val_one - val_two;val_one = val_one - val_two;Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two);

Complete Code:

using System;public class Program { public static void Main(string[] args) { var val_one = 123; var val_two = 234; val_one += val_two; val_two = val_one - val_two; val_one = val_one - val_two; Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two); }}

Output:

The value after swapping is: 234 and -> 123

You can notice how this uses simple arithmetic to stop using temporary variables while swapping. On the other hand, this may become ineffective if there are very large accurate values, and using such arithmetic may result in the loss of some values.

If you want to hide the implementation and not just remove the use of a temporary variable, you can use something such as the following.

Use a Function to Swap Values Rather Than Explicit Implementation to Hide Temporary Variable Use in C#

You can do something as follows.

static void swap(ref int x, ref int y) { var temp = x; x = y; y = temp;}

And then call it below as:

swap(ref val_one, ref val_two);Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two);

Complete Code:

using System;public class Program { public static void Main(string[] args) { var val_one = 123; var val_two = 234; swap(ref val_one, ref val_two); Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two); } static void swap(ref int x, ref int y) { var temp = x; x = y; y = temp; }}

Output:

The value after swapping is: 234 and -> 123

How to Use the XOR Operator to Swap in C#

Let’s look at the code below.

val_one ^= val_two ^= val_one ^= val_two;

Complete Code:

using System;public class Program { public static void Main(string[] args) { var val_one = 123; var val_two = 234; val_one ^= val_two ^= val_one ^= val_two; Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two); }}

And its output:

The value after swapping is: 0 and -> 123

You’ll notice that the first value is 0 even though the second variable now has the value of the first variable and works properly.

So how do we fix this? Let’s first write a code as follows.

val_one ^= val_two;val_two ^= val_one;val_one ^= val_two;

Complete Code:

using System;public class Program { public static void Main(string[] args) { var val_one = 123; var val_two = 234; val_one ^= val_two; val_two ^= val_one; val_one ^= val_two; Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two); }}

And now the output is:

The value after swapping is: 234 and -> 123

So what’s going on? Let’s first understand the code given in the first statement.

That can be expanded as follows.

val_one = val_one ^ val_two;val_two = val_two ^ val_one;val_one = val_one ^ val_two;

Now you can say that the first code is similar to the one presented later, then how is it not working, but the latter performs well?

A change in the order of these arithmetic operations can give different results. In the former code, val_one has an XOR with itself, thus having the result as 0.

In the latter, however, the order is defined already, and values are calculated perfectly, hence the difference.

However, remember not to use XOR swapping for higher code levels. It is unsafe and should be kept as a substitute.

How to Swap Variable Values Without the Use of Temporary Variable in C# (2024)

FAQs

How do you swap without using temporary variables? ›

Without using temporary variable, with addition-subtraction void swap(int &a, int &b) { a = a + b; b = a - b; a = a - b; } 3. Without using temporary variable, with multiplication-division void swap(int &a, int &b) { a = a * b; b = a / b; a = a / b; } 4.

How to swap two values in C#? ›

There are two common ways to swap two numbers without using third variable:
  1. By + and -
  2. By * and /

How to swap two characters in C without using third variable? ›

char a = 'S', b = 'O'; swap(&a, &b); assert(a == 'O'); assert(b == 'S'); Using the exact swap function you provided.

How to swap the values of 2 variables without using additional variables? ›

Using arithmetic operators

Swapping two variables without using a third variable. The arithmetic operators for addition and subtraction can be used to perform the swap without using a third variable. Similarly, multiplication and division can be used to perform the swap without using the third variable.

Can swapping of two numbers be done without using a temporary variable? ›

We can swap two numbers without using third variable. There are two common ways to swap two numbers without using third variable: By + and - By * and /

Can we swap values of two variables without using the temporary third variable? ›

Another approach to swapping values is by using arithmetic operations. Here we are making use of addition and subtraction to perform the swap without the need for an extra variable. In this method, the sum of a and b is assigned to a and then b is updated to the difference between the new a and the old b .

How to swap values of 2 variables without using third variable? ›

Example: Suppose, there are two numbers 25 and 23. X= 25 (First number), Y= 23 (second number) Swapping Logic: X = X + Y = 25 +23 = 48 Y = X - Y = 48 - 23 = 25 X = X -Y = 48 - 25 = 23 and the numbers are swapped as X =23 and Y =25.

What is the swap method in C#? ›

A Swap method exchanges array element values. It acts on 2 separate elements so that they both are still present but in opposite locations. In the C# language, there is no built-in method for this purpose on most types. You have to implement a custom swap method for string characters and other types.

How do you swap two values? ›

We swap two numbers by storing the value of one number in a temporary variable, assigning the value of the second number to the first number, and then assigning the value stored in the temporary variable to the second number.

How to replace first two characters in a string in C#? ›

How to replace the first instance of a string in C#.NET
  1. public static string ReplaceFirst(string str, string term, string replace)
  2. {
  3. int position = str. IndexOf(term);
  4. if (position < 0)
  5. {
  6. return str;
  7. }
  8. str = str. Substring(0, position) + replace + str. Substring(position + term. Length);

How to replace one character with another in C#? ›

Replace(string oldString, string newString); The . Replace() method takes the original string returns a new string with the following changes in it: All occurrences of indicated character are replaced with another one.

How to swap without using third variable? ›

We can swap two numbers without using third variable using Bitwise XOR Operator. Let's first see an example of an XOR operation on two binary numbers. a = 3 => 0011 in binary. b = 5 => 0101 in binary.

How do I swap two strings without temp? ›

Algorithm
  1. Define two strings that need to be swapped.
  2. Concatenate both the strings and store it in first string.
  3. Extract the string from indexes 0 to length (string1) - (string2) using substring function and store it in string 2.

How to swap two numbers without using temp variable using Java? ›

Example 2: Swap Two Numbers in Java Without Using a Temporary Variable
  1. Add num1 and num2 and assign the result back to num1.
  2. Subtract num2 from the updated value of num1 and assign the result back to num2.
  3. Subtract the updated value of num2 from the updated value of num1 and assign the result back to num1.

How would you swap 2 strings without a temporary variable in Java? ›

How do you swap two string variables without using third or temp variable in java?
  1. public class SwapWithoutTemp {
  2. public static void main(String args[]) {
  3. String a = "Love";
  4. String b = "You";
  5. System.out.println("Before swap: " + a + " " + b);
  6. a = a + b;
  7. b = a.substring(0, a.length() - b.length());

How do you swap variables without temp in Python? ›

Without a temporary variable (Tuple swap)

Another way to swap the values of two variables, without using a temporary variable, is to use tuple packing and sequence unpacking. Tuples can be constructed in a number of ways, one of which is by separating tuple items using commas.

How do you swap 3 numbers without using the fourth variable? ›

The bitwise XOR operator can be used to swap three variables. The idea is similar to method 1. We first store XOR of all numbers in 'a'. Then we get individual numbers by doing XOR of this with other two numbers.

References

Top Articles
Latest Posts
Article information

Author: Pres. Carey Rath

Last Updated:

Views: 6417

Rating: 4 / 5 (41 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Pres. Carey Rath

Birthday: 1997-03-06

Address: 14955 Ledner Trail, East Rodrickfort, NE 85127-8369

Phone: +18682428114917

Job: National Technology Representative

Hobby: Sand art, Drama, Web surfing, Cycling, Brazilian jiu-jitsu, Leather crafting, Creative writing

Introduction: My name is Pres. Carey Rath, I am a faithful, funny, vast, joyous, lively, brave, glamorous person who loves writing and wants to share my knowledge and understanding with you.