C# Out Parameter
In C#, the out keyword is used to pass an argument as a reference type. This allows a method to modify the passed argument and return a value to the calling code. In this tutorial, we'll discuss how to use C# out parameters and provide an example.
Syntax
The syntax for using an out parameter in C# is as follows:
public void Method(out int result) {
// code
}
The out keyword is added before the parameter name to indicate that the value passed is of a reference type.
Example
Let's say we want to create a method that takes two integer inputs, calculates the sum, and returns the result to the calling code using an out parameter. Here's how we can implement it:
public void Add(int a, int b, out int result) {
result = a + b;
}
Now, we can call the Add method and pass the result as an out parameter:
int result;
Add(5, 10, out result);
Console.WriteLine(result); // Output: 15
Output
When we run the example code above, the output will be:
15
This is because the Add method calculated the sum of the two integer inputs and assigned the result to the out parameter, which was then printed to the console.
Explanation
In the example above, we created a method called Add which takes two integer inputs, calculates the sum, and returns the result to the calling code using an out parameter. The out keyword is used before the result parameter to indicate that it is of reference type.
We then called the Add method and passed the result parameter as an out parameter. The Add method calculated the sum of the two integer inputs and assigned the result to the out parameter. Finally, we printed the result to the console.
Use
Out parameters are useful when you want to return multiple values from a method, or when you want to modify the value of a parameter that was passed to a method.
Important Points
- When using out parameters, make sure to assign a value to the parameter before exiting the method, otherwise, you'll get a compile-time error.
- Out parameters can't be used as part of an expression, as they must be assigned a value before they can be used.
- Out parameters must be declared before any other parameter of the same data type.
Summary
In this tutorial, we discussed how to use C# out parameters and provided an example. We covered the syntax, example, output, explanation, use, important points, and summary of C# out parameters. With this knowledge, you can now use out parameters in your C# code to pass arguments as reference types and modify them in a method.