Home > Backend Development > C#.Net Tutorial > How are parameters passed in C#?

How are parameters passed in C#?

WBOY
Release: 2023-09-07 23:09:07
forward
820 people have browsed it

How are parameters passed in C#?

Parameters are passed by value or reference in C#. This way, you can also pass parameters using out parameters and param arrays -

Value

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

Reference

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

Out

The return statement can be used to return only a value from a function. However, using output parameters you can return two values ​​from the function. Output parameters are similar to reference parameters, except they pass data out of a method instead of into it.

Param

When declaring a method, you are not sure of the number of parameters passed as parameters. The C# param array gives you an idea of ​​this.

Here is a 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();
      }
   }
}
Copy after login

The above is the detailed content of How are parameters passed in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template