Parameters allow information to be passed into and out of a method. When you define a method, you can include a list of parameters in parentheses following the method name. I will show how to declare parameters and how to call methods with parameters.
Declaring Parameters
Each parameter has a type and a name. You declare parameters by placing the parameter declarations inside the parentheses that follow the name of the method. The syntax that is used to declare parameters is similar to the syntax that is used for example to declare local variables, except that you separate each parameter declaration with a comma instead of with a semicolon.
The following example shows how to declare a method with parameters:
static void MethodWithParameters(int n, string y)
{
// …
}
This example declares the MethodWithParameters method with two parameters: n and y. The first parameter is of type int, and the second is of type string. Note that commas separate each parameter in the parameter list.
Calling Methods with Parameters
The calling code must supply the parameter values when the method is called. The following code shows two examples of how to call a method with parameters. In each case, the values of the parameters are found and placed into the parameters n and y at the start of the execution of MethodWithParameters.
MethodWithParameters(2, “Hello, world”);
int p = 7;
string s = “Test message”;
MethodWithParameters(p, s);
Mechanisms for Passing Parameters

Parameters can be passed in three different ways:
By value – Value parameters are sometimes called in parameters because data can be transferred into the method but cannot be transferred out.
By reference – Reference parameters are sometimes called in/out parameters because data can be transferred into the method and out again.
By output – Output parameters are sometimes called out parameters because data can be transferred out of the method but cannot be transferred in.
Pass by Value
In applications, most parameters are used for passing information into a method but not out. Therefore, pass by value is the default mechanism for passing parameters in C#.
Defining Value Parameters
The simplest definition of a parameter is a type name followed by a variable name. This is known as a value parameter. When the method is called, a new storage location is created for each value parameter, and the values of the corresponding expressions are copied into them. The expression supplied for each value parameter must be the same type as the declaration of the value parameter, or a type that can be implicitly converted to that type. Within the method, you can write code that changes the value of the parameter. It will have no effect on any variables outside the method call.
In the following example, the variable x inside AddOne is completely separate from the variable k in Main. The variable x can be changed in AddOne, but this has no effect on k.
static void AddOne(int x)
{
x++;
}
static void Main( )
{
int k = 6;
AddOne(k);
Console.WriteLine(k); // Display the value 6, not 7
}
What Are Reference Parameters?
A reference parameter is a reference to a memory location. Unlike a value parameter, a reference parameter does not create a new storage location. Instead, a reference parameter represents the same location in memory as the variable that is supplied in the method call.
Declaring Reference Parameters
You can declare a reference parameter by using the ref keyword before the type name, as shown in the following example:
static void ShowReference(ref int nId, ref long nCount)
{
// …
}
Using Multiple Parameter Types
The ref keyword only applies to the parameter following it, not to the whole parameter list. Consider the following method, in which nId is passed by reference but longVar is passed by value:
static void OneRefOneVal(ref int nId, long longVar)
{
// …
}
Matching Parameter Types and Values
When calling the method, you supply reference parameters by using the ref keyword followed by a variable. The value supplied in the call to the method
must exactly match the type in the method definition, and it must be a variable,
not a constant or calculated expression.
int x;
long q;
ShowReference(ref x, ref q);
If you omit the ref keyword, or if you supply a constant or calculated expression, the compiler will reject the call, and you will receive an error message similar to the following: “Cannot convert from ‘int’ to ‘ref int.’”
Changing Reference Parameter Values
If you change the value of a reference parameter, the variable supplied by the caller is also changed, because they are both references to the same location in memory. The following example shows how changing the reference parameter also changes the variable:
static void AddOne(ref int x)
{
x++;
}
static void Main( )
{
int k = 6;
AddOne(ref k);
Console.WriteLine(k); // Display the value 7
}
This works because when AddOne is called, its parameter x is set up to refer to the same memory location as the variable k in Main. Therefore, incrementing x will increment k.
Assigning Parameters Before Calling the Method
A ref parameter must be definitively assigned at the point of call; that is, the compiler must ensure that a value is assigned before the call is made. The following example shows how you can initialize reference parameters before calling the method:
static void AddOne(ref int x)
{
x++;
}
static void Main( )
{
int k = 6;
AddOne(ref k);
Console.WriteLine(k); // 7
}
The following example shows what happens if a reference parameter k is not initialized before its method AddOne is called:
int k;
AddOne(ref k);
Console.WriteLine(k);
The C# compiler will reject this code and display the following error message: “Use of unassigned local variable ‘k.‘”
Output Parameters
What Are Output Parameters?
Output parameters are like reference parameters, except that they transfer data out of the method rather than into it. Like a reference parameter, an output parameter is a reference to a storage location supplied by the caller. However, the variable that is supplied for the out parameter does not need to be assigned a value before the call is made, and the method will assume that the parameter has not been initialized on entry.
Output parameters are useful when you want to be able to return values from a method by means of a parameter without assigning an initial value to the parameter.
Using Output Parameters
To declare an output parameter, use the keyword out before the type and name, as shown in the following example:
static void OutDemo(out int p)
{
// …
}
As with the ref keyword, the out keyword only affects one parameter, and each out parameter must be marked separately.
When calling a method with an out parameter, place the out keyword before the variable to be passed, as in the following example.
int n;
OutDemo(out n);
In the body of the method being called, no initial assumptions are made about the contents of the output parameter. It is treated just like an unassigned local variable. The out parameter must be assigned a value inside the method.
Using Variable-Length Parameter Lists
C# provides a mechanism for passing variable-length parameter lists.
Declaring Variable-Length Parameters
It is sometimes useful to have a method that can accept a varying number of parameters. In C#, you can use the params keyword to specify a variablelength parameter list. When you declare a variable-length parameter, you must:
- Declare only one params parameter per method.
- Place the parameter at the end of the parameter list.
- Declare the parameter as a single-dimension array type.
The following example shows how to declare a variable-length parameter list:
static long AddList(params long[ ] v)
{
long total;
long i;
for (i = 0, total = 0; i < v. Length; i++)
total += v[i];
return total;
}
Because a params parameter is always an array, all values must be the same type.
Passing Values
When you call a method with a variable-length parameter, you can pass values to the params parameter in one of two ways:
- As a comma separated list of elements (the list can be empty)
- As an array
The following code shows both techniques. The two techniques are treated in exactly the same way by the compiler.
static void Main( )
{
long x;
x = AddList(63, 21, 84); // List
x = AddList(new long[ ]{ 63, 21, 84 }); // Array
}
Regardless of which method you use to call the method, the params parameter is treated like an array. You can use the Length property of the array to determine how many parameters were passed to each call.
In a params parameter, a copy of the data is made, and although you can modify the values inside the method, the values outside the method are unchanged.
Using Methods with Output Parameters
We will write a new method called Factorial that takes an int value and calculates its factorial. The factorial of a number is the product of all the numbers between 1 and that number. The factorial of zero is defined to be 1.
The following are examples of factorials:
Factorial(0) = 1
Factorial(1) = 1
Factorial(2) = 1 * 2 = 2
Factorial(3) = 1 * 2 * 3 = 6
Factorial(4) = 1 * 2 * 3 * 4 = 24
namespace Utils
{
using System;
public class Utils
{
//
// Calculate factorial
// and return the result as an out parameter
//
public static bool Factorial(int n, out int answer)
{
int k; // Loop counter
int f; // Working value
bool ok=true; // True if okay, false if not
// Check the input value
if (n<0) ok = false;
// Calculate the factorial value as the
// product of all of the numbers from 2 to n
try
{
//checked
f = 1;
for (k=2; k<=n; ++k)
{
f = f * k;
}
}
catch(Exception)
{
// If something goes wrong in the calculation,
// catch it here. All exceptions
// are handled the same way: set the result
// to zero and return false.
f = 0;
ok = false;
}
// Assign result value
answer = f;
// Return to caller
return ok;
}
}
}
To test the Factorial method:
namespace Utils
{
public class Test
{
static void Main( )
{
int f; // Factorial result
bool ok; // Factorial success or failure
… existing code omitted for clarity …
// Get input for factorial
Console.WriteLine(“Number for factorial:”);
x = int.Parse(Console.ReadLine( ));
// Test the factorial function
ok = Utils.Factorial(x, out f);
// Output factorial results
if (ok)
Console.WriteLine(“Factorial(” + x + “) = ” + f);
else
Console.WriteLine(“Cannot compute this_factorial”);
}
}
}