How are parameters passed in C#?

CsharpProgrammingServer Side Programming

Parameters are passed in C# either by value or by reference. With that, you can also use out parameters and param array to pass parameters −

Value

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

Reference

This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.

Out

A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function. Output parameters are similar to reference parameters, except that they transfer data out of the method rather than into it.

Param

While declaring a method, you are not sure of the number of arguments passed as a parameter. C# param arrays can let you know about this.

The following is the complete example to learn how to implement param in C# −

Example

using System;

namespace Program {
   class ParamArray {
      public int AddElements(params int[] arr) {
         int sum = 0;

         foreach (int i in arr) {
            sum += i;
         }
         return sum;
      }
   }

   class Demo {
      static void Main(string[] args) {
         ParamArray app = new ParamArray();
         int sum = app.AddElements(300, 250, 350, 600, 120);

         Console.WriteLine("The sum is: {0}", sum);
         Console.ReadKey();
      }
   }
}
raja
Published on 13-Aug-2018 16:41:28
Advertisements