How do we pass parameters by value in a C# method?

CsharpProgrammingServer Side Programming

<p>This is the default mechanism for passing parameters to a method. In this mechanism, when a method is called, a new storage location is created for each value parameter.</p><p>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. The following is the code to pass parameters by value.</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/FhmrOI" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">using System; namespace CalculatorApplication { &nbsp; &nbsp;class NumberManipulator { &nbsp; &nbsp; &nbsp; public void swap(int x, int y) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int temp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;temp = x; /* save the value of x */ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;x = y; /* put y into x */ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;y = temp; /* put temp into y */ &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; static void Main(string[] args) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;NumberManipulator n = new NumberManipulator(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;/* local variable definition */ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int a = 100; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int b = 200; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(&quot;Before swap, value of a : {0}&quot;, a); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(&quot;Before swap, value of b : {0}&quot;, b); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;/* calling a function to swap the values */ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;n.swap(a, b); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(&quot;After swap, value of a : {0}&quot;, a); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(&quot;After swap, value of b : {0}&quot;, b); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.ReadLine(); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 100 After swap, value of b : 200</pre>
raja
Updated on 23-Jun-2020 14:32:38

Advertisements