Advertisement
stefanpu

Swaping reference and type in static method

Jan 9th, 2013
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.29 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication1
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             List<int> noSwapList = new List<int>() { 1, 2 };
  13.  
  14.             //Swap value types - no modification to list.
  15.             Swap(noSwapList[0], noSwapList[1]);
  16.             Console.WriteLine("No swap occures");
  17.             PrintList(noSwapList);
  18.  
  19.             //Swap ref types - modification to list.
  20.             Swap(noSwapList, 0, 1);
  21.             Console.WriteLine("Swap occures");
  22.             PrintList(noSwapList);
  23.  
  24.  
  25.         }
  26.  
  27.         private static void PrintList(List<int> noSwapList)
  28.         {
  29.             Console.WriteLine();
  30.             foreach (var item in noSwapList)
  31.             {
  32.                 Console.Write(item + " ");                
  33.             }
  34.             Console.WriteLine();
  35.         }
  36.  
  37.         static void Swap(int a, int b)
  38.         {
  39.             int temp = a;
  40.             a = b;
  41.             b = temp;
  42.         }
  43.  
  44.         static void Swap(List<int> list, int firstIndex, int secondIndex)
  45.         {
  46.             int temp = list[firstIndex];
  47.             list[firstIndex] = list[secondIndex];
  48.             list[secondIndex] = temp;
  49.         }
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement