C# in and out
In parameter in C#
To indicate that a method parameter is supplied by reference but cannot be modified by the called method, use the in keyword in C#. This is helpful for parameters that need to be supplied by reference for the calling method to get the results even when they are not changed by the called method.
With the introduction of "in parameter" in C# 7.2, read-only references to variables can now be passed. Before C# 7.2, we passed a variable's references using the "ref" and "out" keywords. "Out" is just intended for output, but "ref" is intended for both input and output. There was, however, no direct choice available if we needed to give a read-only reference—that is, a variable that was passed as input only. For this reason, the term "in parameter" has been introduced in C# 7.2.
Employing a value type variable and the "in" parameter.
using System;
class Program
{
static void Main(string[] args)
{
int p = 23, q = 14, r = 6;
Console.Write($"{p} + {q} + {r}: ");
Add(p, q, ref r);
Console.WriteLine($"{r}");
}
public static void Add(ref readonly int a, ref readonly int b, ref int c)
{
c = a + b + c;
}
}
Except for Visual Studio 2017 version 15.5 Preview 1, it will not function with later releases of Visual Studio 2017 version 15.5 or higher versions.
Simply substitute "in" with the keyword "ref read-only" and recompile the code. The code snippet below will appear once "in" has been used instead of "ref read-only."
using System;
class Program
{
static void Main(string[] args)
{
int p = 23, q = 14, r = 6;
Console.Write($"{p} + {q} + {r}: ");
Add(p, q, ref r);
Console.WriteLine($"{r}");
}
public static void Add(in int a, in int b, ref int c)
{
c = a + b + c;
}
}
Output:
![C# in and out](https://static.tutorialandexample.com/csharp/csharp-in-and-out1.png)
The compiler can pass a read-only reference to the argument using the in modifier and generate a temporary variable. When an argument needs to be converted, when there is an implicit conversion from the argument type, or when the argument is a value that isn't a variable, the compiler always creates a temporary variable. For instance, when a literal value or the value obtained from a property accessor is used as the argument. Select the read-only modifier ref rather than in if your API requires the argument to be supplied by reference.
Techniques defined with parameters can optimize performance. Large struct-type arguments may be used, and copying those structures comes at a significant cost when functions are invoked within tight loops or important code pathways. Because the called method doesn't change the argument's state, methods declare in parameters that arguments can be supplied by reference securely. You can avoid making the (perhaps) costly copy by passing those parameters via reference. To ensure the argument is provided by reference rather than by value, you must add the in modifier at the call point. The two effects of explicitly utilizing it are as follows:
- The compiler is forced to choose a method defined with a matching in parameter when an in parameter is specified at the call point. Otherwise, the by-value overload is better when the sole difference between the two methods is the presence of in.
- By adding in, you indicate that you want to transmit an argument by reference. The place directly referenced must be represented by the argument used within. The same general guidelines hold true for out and ref arguments: Constants, regular properties, and other expressions that yield values are not allowed. If not, the compiler is informed that creating a temporary variable to pass via read-only reference to the method is acceptable by omitting it at the call site. The compiler establishes a temporary variable to get around a few limitations in the arguments:
- Compile-time constants can be used as parameters in a temporary variable.
- Properties or alternative expressions for parameters can be used with a temporary variable.
- When there is an implicit conversion from the argument type to the parameter type, a temporary variable accepts arguments.
Out parameter in C#
In C#, the out keyword is utilized to deliver arguments to methods as a reference type. When a method returns numerous values, it is typically used.
Key Points:
- Both the method declaration and the calling method must specifically utilize the out keyword to use it as a parameter.
- Iterator techniques are not permitted to use the out parameters.
- It's comparable to the ref keyword. However, the primary distinction between the ref and out keywords is that the former requires the variable to be initialized before passing it to the method. However, the variables need not be initialized before being supplied to the method via the out parameter. However, the variable needs to be initialized in the called method before it can return a value to the calling method.
- Asynchronous methods are not permitted to use the out parameters.
- The out parameter may be defined inline at the moment the method is called. However, the code block where it calls can also access the inline out parameters.
- With out parameters, overloading a method is also possible.
- It is comparable to the in keyword, but ref permits the method that is called it to modify the parameter value while the in keyword does not.
- Since properties are not variables, they cannot be provided as parameters.
- C# 6.0, a variable could only pass as an out argument unless the user first declared it. However, starting with C# 7.0, the user can define the out variable in the method call's argument list instead of needing to declare it separately.
- A method may contain several out parameters.
using System;
class TE {
// Main method
static public void Main()
{
//defining a variable
// without giving it a value
int x;
//Variable x is passed to the method
//using the out keyword.
Add(out x);
// Print the value x
Console.WriteLine("The value has been added and is: {0}", x);
}
//A method where the out parameter is passed in and
//which returns the passed parameter's value
public static void Add(out int x)
{
x = 15;
x += x;
}
}
Output:
![C# in and out](https://static.tutorialandexample.com/csharp/csharp-in-and-out2.png)
Multiple out parameters:
A method in C# can accept multiple out parameters, which can return numerous values.
Example:
The code below declares two value variables, int x and y, without initializing them. Using the out keyword, we now give these inputs to the Addition method, such as Add(out x, out y);. These variables' values are assigned in the method that they passed.
using System;
class TE {
// Main method
static public void Main()
{
// Variable declaration
// without value assignment
int x, y;
// Multiple variables should be passed to the method
// using the out keyword.
Add(out x, out y);
// Display the values x and y
Console.WriteLine("The value that has been added is: {0}", x);
Console.WriteLine("The value that has been added is: {0}", y);
}
// A method where the arguments are passed in
// and the values of the given
// parameters are returned
public static void Add(out int x, out int y)
{
x = 12;
y = 45;
x += x;
y += y;
}
}
Output:
![C# in and out](https://static.tutorialandexample.com/csharp/csharp-in-and-out3.png)
Improvements to the Out Parameter in C# 7.0:
The following new features have been added to the out parameter in C# 7.0:
- The term "in-line declaration of out parameter" or "implicit type out parameter" refers to the ability of the out parameter in C# 7.0 to function without the need for declaration and initialization. Its scope is restricted to the local scope or the method body.
- The method parameter list permits the usage of the var type for the out parameter.
- It is not required for the name of the out parameter to match in both the definition and the call.
- It's applicable to Try Pattern as well.
Restrictions on in, out, and reference
- Async and iterator methods (e.g., yield return and yield break statements) do not support using the in, out, and ref keywords. Furthermore, unless the parameter is a struct, you cannot use the in keyword in the first parameter of an extension method.
- When determining overloads, it is important to remember that the keywords in, ref, and out are not included in the method signature. Therefore, methods that differ simply in signature concerning these keywords cannot be overloaded.
- Put another way, your code won't compile if you have two methods with the same name, but one takes an integer as an input parameter, and the other takes an integer as an output parameter.