Swapping two variables in one line using C#

WBOY
Release: 2023-08-26 20:01:13
forward
974 people have browsed it

使用 C# 在一行中交换两个变量

To swap two variables in a single line using the Bitwise XOR Operator.

val1 = val1 ^ val2 ^ (val2 = val1);
Copy after login

Above, we have set the values ​​−

int val1 = 30;
int val2 = 60;
Copy after login

The following are Example of swapping variables using one line of code in C#:

Example

using System;

class Demo {

   public static void Main(String[] args) {
      int val1 = 30;
      int val2 = 60;

      Console.WriteLine("Values before swap");
      Console.WriteLine(val1);
      Console.WriteLine(val2);

      val1 = val1 ^ val2 ^ (val2 = val1);

      Console.WriteLine("Values after swap");
      Console.WriteLine(val1);
      Console.WriteLine(val2);
   }
}
Copy after login

The above is the detailed content of Swapping two variables in one line using C#. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!