In how many ways you can pass parameters to a method in c# ?
Rajkiran Swain
Select an image from your device to upload
In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference with the intent of changing the value, use the ref, or out keyword. To pass by reference with the intent of avoiding copying but not changing the value, use the in modifier. For simplicity, only the ref keyword is used in the examples in this topic. For more information about the difference between in, ref, and out, see in, ref, and out.
The following example illustrates the difference between value and reference parameters.
C#
Copyclass Program{ static void Main(string[] args) { int arg;
// Passing by value. // The value of arg in Main is not changed. arg = 4; squareVal(arg); Console.WriteLine(arg); // Output: 4 // Passing by reference. // The value of arg in Main is changed. arg = 4; squareRef(ref arg); Console.WriteLine(arg); // Output: 16 }static void squareVal(int valParameter){ valParameter *= valParameter;}// Passing by referencestatic void squareRef(ref int refParameter){ refParameter *= refParameter;}
// Passing by value.
// The value of arg in Main is not changed.
arg = 4;
squareVal(arg);
Console.WriteLine(arg);
// Output: 4
// Passing by reference.
// The value of arg in Main is changed.
squareRef(ref arg);
// Output: 16
}
static void squareVal(int valParameter)
{
valParameter *= valParameter;
// Passing by reference
static void squareRef(ref int refParameter)
refParameter *= refParameter;