
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Swap two numbers in C#
To swap two numbers, work with the following logic.
Set two variables for swapping −
val1 = 100; val2 = 200;
Now perform the following operation for swap −
val1 = val1 + val2; val2 = val1 - val2; val1 = val1 - val2;
The following is the code −
Example
using System; namespace Demo { class Program { static void Main(string[] args) { int val1,val2; val1 = 100; val2 = 200; Console.WriteLine("Values before swap..."); Console.WriteLine(val1.ToString()); Console.WriteLine(val2.ToString()); val1 = val1 + val2; val2 = val1 - val2; val1 = val1 - val2; Console.WriteLine("Values after swap..."); Console.WriteLine(val1.ToString()); Console.WriteLine(val2.ToString()); Console.ReadLine(); } } }
- Related Articles
- How to Swap Two Numbers in Golang?
- C++ Program to Swap Two Numbers
- Java Program to Swap Two Numbers.
- Haskell Program to Swap Two Numbers
- Kotlin Program to Swap Two Numbers
- How to Swap Two Numbers in Swift Program?
- 8085 program to swap two 8-bit numbers
- Java program to swap two numbers using XOR operator
- How to swap two numbers without using a temp variable in C#
- 8085 program to swap two 8 bit numbers using Direct addressing mode
- 8085 program to swap two 16-bit numbers using Direct addressing mode
- Write a Golang program to swap two numbers without using a third variable
- Swap data between two columns in MySQL?
- How to swap two variables in JavaScript?
- Swap two variables in one line in Java

Advertisements