In C#, an out
parameter is used to pass a value from a method back to the caller, similar to a ref
parameter. However, unlike a ref
parameter, an out
parameter does not require the value to be initialized before it is passed to the method.
The out
keyword is used to specify an out
parameter in a method signature. Here's an example:
csharppublic void Calculate(int input, out int output)
{
// Perform some calculations
output = input * 2;
}
In this example, we define a method called Calculate
that takes an integer input
parameter and an out
integer output
parameter. Inside the method, we perform some calculations and set the value of output
to the result. When the method is called, the output
parameter must be declared and passed to the method as an argument. After the method has completed execution, the value of output
will contain the calculated result.
Here's an example of how to call the Calculate
method:
int input = 5;
int output;
Calculate(input, out output);
Console.WriteLine(output); // Output: 10
In this example, we declare an integer input
variable and pass it to the Calculate
method along with the output
parameter declared as an out
parameter. After the method has completed execution, the value of output
will contain the calculated result, which we can then print to the console.
Comments
Post a Comment