How to pass parameters to a method in C#?

CsharpProgrammingServer Side Programming

To pass parameters to a method in C#, let us see how to pass parameters by value. In this mechanism, when a method is called, a new storage location is created for each value parameter.

The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the method have no effect on the argument.

Here is the example showing how to pass parameters to a method −

Example

 Live Demo

using System;

namespace Demo {
   class NumberManipulator {
      public void swap(int x, int y) {
         int temp;
         temp = x;
         x = y;
         y = temp;
      }
      static void Main(string[] args) {
         NumberManipulator n = new NumberManipulator();
         int a = 50;
         int b = 150;
         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);
         /* calling a function to swap the values */
         n.swap(a, b);
         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);
         Console.ReadLine();
      }
   }
}

Output

Before swap, value of a : 50
Before swap, value of b : 150
After swap, value of a : 50
After swap, value of b : 150
raja
Published on 09-Aug-2018 08:33:34
Advertisements