diff --git a/docs/csharp/language-reference/keywords/in-parameter-modifier.md b/docs/csharp/language-reference/keywords/in-parameter-modifier.md index 7b425dd268c70..c9bfc04f37fa3 100644 --- a/docs/csharp/language-reference/keywords/in-parameter-modifier.md +++ b/docs/csharp/language-reference/keywords/in-parameter-modifier.md @@ -18,10 +18,10 @@ The `in` keyword causes arguments to be passed by reference. It is like the [ref [!code-csharp-interactive[cs-in-keyword](../../../../samples/snippets/csharp/language-reference/keywords/in-ref-out-modifier/InParameterModifier.cs#1)] -The preceding example demonstrates that the `in` modifier is unnecessary at the call site. It is only required in the method declaration. +The preceding example demonstrates the `in` modifier is usually unnecessary at the call site. It is only required in the method declaration. > [!NOTE] -> The `in` keyword can also be used with a generic type parameter to specify that the type parameter is contravariant, as part of a `foreach` statement, or as part of a `join` clause in a LINQ query. For more information on the use of the `in` keyword in these contexts, see [in](in.md) which provides links to all those uses. +> The `in` keyword can also be used with a generic type parameter to specify that the type parameter is contravariant, as part of a `foreach` statement, or as part of a `join` clause in a LINQ query. For more information on the use of the `in` keyword in these contexts, see [in](in.md), which provides links to all those uses. Variables passed as `in` arguments must be initialized before being passed in a method call. However, the called method may not assign a value or modify the argument. @@ -37,36 +37,91 @@ class CS0663_Example } ``` -Overloading based on the presence of `in` is allowed, but generates a compiler warning: +Overloading based on the presence of `in` is allowed: ```csharp class InOverloads { - // Discouraged. Calling SampleMethod(value) is ambiguous. public void SampleMethod(in int i) { } public void SampleMethod(int i) { } } ``` -Properties or constants may be passed as `in` parameters, because the calling method may not modify their values. - -You can't use the `in`, `ref`, and `out` keywords for the following kinds of methods: - -- Async methods, which you define by using the [async](../../../csharp/language-reference/keywords/async.md) modifier. - -- Iterator methods, which include a [yield return](../../../csharp/language-reference/keywords/yield.md) or `yield break` statement. +## Overload resolution rules + +You can understand the overload resolution rules for methods with by value vs. `in` arguments through understanding the motivation for `in` arguments. Defining methods using `in` parameters is a potential performance optimization. Some `struct` type arguments may be large in size, and when methods are called in tight loops or critical code paths, the cost of copying those structures is critical. Methods declare `in` parameters to specify that arguments may be passed by reference safely because the called method does not modify the state of that argument. Passing those arguments by reference avoids the (potentially) expensive copy. + +Specifying `in` on arguments at the call site is typically optional. There is no semantic difference between passing arguments by value and passing them by reference using the `in` modifier. The `in` modifier at the call site is optional because you don't need to indicate that the argument's value might be changed. You explicitly add the `in` modifier at the call site to ensure the argument is passed by reference, not by value. Explicitly using `in` has two effects: + +First, specifying `in` at the call site forces the compiler to select a method defined with a matching `in` parameter. Otherwise, when two methods differ only in the presence of `in`, the by value overload is a better match. + +Second, specifying `in` declares your intent to pass an argument by reference. The argument used with `in` must represent a location that can be directly referred to. The same general rules for `out` and `ref` arguments apply: You cannot use constants, ordinary properties, or other expressions that produce values. Otherwise, omitting `in` at the call site informs the compiler that you will allow it to create a temporary variable to pass by read-only reference to the method. The compiler creates a temporary variable to overcome several restrictions with `in` arguments: -You typically declare `in` arguments to avoid the copy operations necessary for passing arguments by value. This is most useful when arguments are value types such as structures where copy operations are more expensive than passing by reference. +- A temporary variable allows compile-time constants as `in` parameters. +- A temporary variable allows properties, or other expressions for `in` parameters. +- A temporary variable allows arguments where there is an implicit conversion from the argument type to the parameter type. + +In all the preceding instances, the compiler creates a temporary variable that stores the value of the constant, property, or other expression. + +The following code illustrates these rules: + +```csharp +static void Method(in int argument) +{ + // implementation removed +} + +Method(5); // OK, temporary variable created. +Method(5L); // CS1503: no implicit conversion from long to int +short s = 0; +Method(s); // OK, temporary int created with the value 0 +Method(in s); // CS1503: cannot convert from in short to in int +int i = 42; +Method(i); // passed by readonly reference +Method(in i); // passed by readonly reference, explicitly using `in` +``` -> [!WARNING] -> `in` parameters can be even more expensive if misused. The compiler may not know if member methods modify the state of the struct. Whenever the compiler cannot ensure that the object is not modified, it defensively creates a copy and calls member references using that copy. Any possible modifications are to that defensive copy. The two ways to avoid these copies are to pass `in` parameters as `in` arguments or to define structures as `readonly struct`. +Now, suppose another method using by value arguments was available. The results change as shown in the following code: + +```csharp +static void Method(int argument) +{ + // implementation removed +} + +static void Method(in int argument) +{ + // implementation removed +} + +Method(5); // Calls overload passed by value +Method(5L); // CS1503: no implicit conversion from long to int +short s = 0; +Method(s); // Calls overload passed by value. +Method(in s); // CS1503: cannot convert from in short to in int +int i = 42; +Method(i); // Calls overload passed by value +Method(in i); // passed by readonly reference, explicitly using `in` +``` + +The only method call where the argument is passed by reference is the final one. + +> [!NOTE] +> The preceding code uses `int` as the argument type for simplicity. Because `int` is no larger than a reference in most modern machines, there is no benefit to passing a single `int` as a readonly reference. + +## Limitations on `in` parameters + +You can't use the `in`, `ref`, and `out` keywords for the following kinds of methods: + +- Async methods, which you define by using the [async](async.md) modifier. +- Iterator methods, which include a [yield return](yield.md) or `yield break` statement. ## C# Language Specification [!INCLUDE[CSharplangspec](~/includes/csharplangspec-md.md)] ## See Also - [C# Reference](../../../csharp/language-reference/index.md) - [C# Programming Guide](../../../csharp/programming-guide/index.md) - [C# Keywords](../../../csharp/language-reference/keywords/index.md) - [Method Parameters](../../../csharp/language-reference/keywords/method-parameters.md) - [Reference Semantics with Value Types](../../../csharp/reference-semantics-with-value-types.md) + [C# Reference](../index.md) + [C# Programming Guide](../../programming-guide/index.md) + [C# Keywords](index.md) + [Method Parameters](method-parameters.md) + [Reference Semantics with Value Types](../../reference-semantics-with-value-types.md) diff --git a/docs/csharp/language-reference/keywords/in.md b/docs/csharp/language-reference/keywords/in.md index c43685ac975bb..10254021a2f76 100644 --- a/docs/csharp/language-reference/keywords/in.md +++ b/docs/csharp/language-reference/keywords/in.md @@ -16,7 +16,7 @@ ms.author: "wiwagn" # in (C# Reference) -The `in` contextual keyword is used in four contexts: +The `in` keyword is used in four contexts: - [generic type parameters](in-generic-modifier.md) in generic interfaces and delegates. - As a [parameter modifier](in-parameter-modifier.md), which lets you pass an argument to a method by reference rather than by value. diff --git a/docs/csharp/language-reference/keywords/method-parameters.md b/docs/csharp/language-reference/keywords/method-parameters.md index e3a58e61eb87b..df45dcb45ec42 100644 --- a/docs/csharp/language-reference/keywords/method-parameters.md +++ b/docs/csharp/language-reference/keywords/method-parameters.md @@ -20,13 +20,13 @@ Parameters declared for a method without [in](../../../csharp/language-reference This section describes the keywords you can use when declaring method parameters: -- [params](../../../csharp/language-reference/keywords/params.md) +- [params](../../../csharp/language-reference/keywords/params.md) specifies that this parameter may take a variable number of arguments. -- [in](../../../csharp/language-reference/keywords/in-parameter-modifier.md) +- [in](../../../csharp/language-reference/keywords/in-parameter-modifier.md) specifies that this parameter is passed by reference but is only read by the called method. -- [ref](../../../csharp/language-reference/keywords/ref.md) +- [ref](../../../csharp/language-reference/keywords/ref.md) specifies that this parameter is passed by reference and may be read or written by the called method. -- [out](../../../csharp/language-reference/keywords/out-parameter-modifier.md) +- [out](../../../csharp/language-reference/keywords/out-parameter-modifier.md) specifies that this parameter is passed by reference and is written by the called method. ## See Also [C# Reference](../../../csharp/language-reference/index.md) diff --git a/docs/csharp/language-reference/keywords/out.md b/docs/csharp/language-reference/keywords/out.md index 081b9c9f6f4ff..cb7cab3b4cc82 100644 --- a/docs/csharp/language-reference/keywords/out.md +++ b/docs/csharp/language-reference/keywords/out.md @@ -17,7 +17,7 @@ author: "BillWagner" ms.author: "wiwagn" --- # out (C# Reference) -You can use the `out` contextual keyword in two contexts: +You can use the `out` keyword in two contexts: - As a [parameter modifier](../../../csharp/language-reference/keywords/out-parameter-modifier.md), which lets you pass an argument to a method by reference rather than by value. diff --git a/docs/csharp/reference-semantics-with-value-types.md b/docs/csharp/reference-semantics-with-value-types.md index ec69f4e5f1779..0e5df4304a8a9 100644 --- a/docs/csharp/reference-semantics-with-value-types.md +++ b/docs/csharp/reference-semantics-with-value-types.md @@ -14,17 +14,17 @@ ms.custom: mvc # Reference semantics with value types An advantage to using value types is that they often avoid heap allocations. -The corresponding disadvantage is that they are copied by value. This tradeoff +The disadvantage is that they are copied by value. This tradeoff makes it harder to optimize algorithms that operate on large amounts of data. New language features in C# 7.2 provide mechanisms that enable pass-by-reference -semantics with value types. If you use these features wisely you can minimize both allocations +semantics with value types. Use these features wisely to minimize both allocations and copy operations. This article explores those new features. Much of the sample code in this article demonstrates features added in C# 7.2. In order to -use those features, you have to configure your project to use C# 7.2 or later in your -project. You can use Visual Studio to select it. For each project, select **Project** from +use those features, you must configure your project to use C# 7.2 or later. +You can use Visual Studio to select it. For each project, select **Project** from the menu, then **Properties**. Select the **Build** tab and click **Advanced**. From there, -you can configure the language version. Choose either "7.2", or "latest". Or you can +configure the language version. Choose either "7.2", or "latest". Or you can edit the *csproj* file and add the following node: ```XML @@ -35,17 +35,17 @@ edit the *csproj* file and add the following node: You can use either "7.2" or "latest" for the value. -## Specifying `in` parameters +## Passing arguments by readonly reference C# 7.2 adds the `in` keyword to complement the existing `ref` -and `out` keywords when you write a method that passes arguments -by reference. The `in` keyword specifies that you are passing -the parameter by reference and the called method does not modify -the value passed to it. +and `out` keywords to pass arguments +by reference. The `in` keyword specifies passing +the argument by reference, but the called method does not modify +the value. This addition provides a full vocabulary to express your design intent. -Value types are copied when passed to a called method when you do not -specify any of the following modifiers. Each of these modifiers specify +Value types are copied when passed to a called method when you don't +specify any of the following modifiers in the method signature. Each of these modifiers specifies that a value type is passed by reference, avoiding the copy. Each modifier expresses a different intent: @@ -53,8 +53,8 @@ expresses a different intent: - `ref`: This method may set the value of the argument used as this parameter. - `in`: This method does not modify the value of the argument used as this parameter. -When you add the `in` modifier to pass an argument by reference, you declare -your design intent is to pass arguments by reference to +Add the `in` modifier to pass an argument by reference and declare +your design intent to pass arguments by reference to avoid unnecessary copying. You do not intend to modify the object used as that argument. The following code shows an example of a method that calculates the distance between two points in 3D space. @@ -62,7 +62,7 @@ that calculates the distance between two points in 3D space. [!code-csharp[InArgument](../../samples/csharp/reference-semantics/Program.cs#InArgument "Specifying an In argument")] The arguments are two structures that each contain three doubles. A double is 8 bytes, -so each argument is 24 bytes. By specifying the `in` modifier, you pass 4-byte +so each argument is 24 bytes. By specifying the `in` modifier, you pass a 4-byte or 8-byte reference to those arguments, depending on the architecture of the machine. The difference in size is small, but it can quickly add up when your application calls this method in a tight loop using many different @@ -88,19 +88,47 @@ temporary variable created as part of the method call. There are several ways in which the compiler ensures that the read-only nature of an `in` argument is enforced. First of all, the called method can't directly assign to an `in` parameter. It can't directly assign -to any field of an `in` parameter. In addition, you cannot pass -an `in` parameter to any method demanding the `ref` or `out` modifier. -The compiler enforces that the `in` argument is a readonly variable. You -can call any instance method that uses pass-by-value semantics. In +to any field of an `in` parameter when that value is a `struct` type. In addition, you cannot pass +an `in` parameter to any method using the `ref` or `out` modifier. +These rules apply to any field of an `in` parameter, provided the +field is a `struct` type and the parameter is also a `struct` type. In fact, these rules +apply for multiple layers of member access provided the types at all levels +of member access are `structs`. +The compiler enforces that `struct` types passed as `in` arguments and their +`struct` members are read-only variables when used as arguments to other methods. + +The use of `in` parameters avoids the potential performance costs +of making copies. It does not change the semantics of any method call. Therefore, +you do not need to specify the `in` modifier at the call site. However, +omitting the `in` modifier at the call site informs the compiler that it is +allowed to make a copy of the argument for the following reasons: + +- There is an implicit conversion but not an identity conversion from the argument type to the parameter type. +- The argument is an expression but does not have a known storage variable. +- An overload exists that differs by the presence or absence of `in`. In that case, the by value overload is a better match. + +These rules are useful as you update existing code to use read-only +reference arguments. Inside the called method, you can call any instance +method that uses by value parameters. In those instances, a copy of the `in` parameter is created. Because the compiler can create a temporary variable for any `in` parameter, you can also specify default -values for any `in` parameter. The follow code uses that to specify the origin +values for any `in` parameter. The following code specifies the origin (point 0,0) as the default value for the second point: [!code-csharp[InArgumentDefault](../../samples/csharp/reference-semantics/Program.cs#InArgumentDefault "Specifying defaults for an in parameter")] -The `in` parameter designation can also be used with reference types or built in -numeric values. However, the benefits in both cases are minimal, if any. +To force the compiler to pass read only arguments by reference, specify the `in` modifer +on the arguments at the call site, as shown in the following code: + +[!code-csharp[UseInArgument](../../samples/csharp/reference-semantics/Program.cs#ExplicitInArgument "Specifying an In argument")] + +This behavior makes it easier to adopt `in` parameters over time in large +codebases where performance gains are possible. You add the `in` modifier +to method signatures first. Then, you can add the `in` modifier at callsites +and create `readonly struct` types to enable the compiler to avoid creating +defensive copies of `in` parameters in more locations. + +The `in` parameter designation can also be used with reference types or numeric values. However, the benefits in both cases are minimal, if any. ## `ref readonly` returns @@ -111,7 +139,8 @@ that you are returning a reference to existing data, but not allowing modification. The compiler enforces that the caller cannot modify the reference. Attempts -to assign to the value directly generate a compile-time error. However, the compiler cannot know if any member method modifies the state of the struct. +to assign the value directly generate a compile-time error. However, the compiler +cannot know if any member method modifies the state of the struct. To ensure that the object is not modified, the compiler creates a copy and calls member references using that copy. Any modifications are to that defensive copy. @@ -131,20 +160,20 @@ not declared with the `ref readonly` modifier. The compiler generates code to copy the object as part of the assignment. When you assign a variable to a `ref readonly return`, you can specify either a `ref readonly` -variable, or a by-value copy of the readonly reference: +variable, or a by-value copy of the read-only reference: [!code-csharp[AssignRefReadonly](../../samples/csharp/reference-semantics/Program.cs#AssignRefReadonly "Assigning a ref readonly")] The first assignment in the preceding code makes a copy of the `Origin` constant and assigns that copy. The second assigns a reference. Notice that the `readonly` modifier must be part of the declaration of the variable. The reference to which it refers -cannot be modified. Attempts to do so result in a compile-time error. +can't be modified. Attempts to do so result in a compile-time error. ## `readonly struct` type Applying `ref readonly` to high-traffic uses of a struct may be sufficient. Other times, you may want to create an immutable struct. Then you can -always pass by readonly reference. That practice +always pass by read-only reference. That practice removes the defensive copies that take place when you access methods of a struct used as an `in` parameter. @@ -172,7 +201,7 @@ Another related language feature is the ability to declare a value type that must be stack allocated. In other words, these types can never be created on the heap as a member of another class. The primary motivation for this feature was and related structures. may contain a managed pointer as one of its members, the other being -the length of the span. It's actually implemented a bit differently because C# +the length of the span. It's implemented a bit differently because C# doesn't support pointers to managed memory outside of an unsafe context. Any write that changes the pointer and the length is not atomic. That means a would be subject to out of range errors or other type safety violations @@ -185,7 +214,7 @@ when using memory from interop APIs. You can define your own `ref struct` types for those needs. In this article, you see examples using `Span` for simplicity. -The `ref struct` declaration declares that a struct of this type must be +The `ref struct` declaration declares a struct of this type must be on the stack. The language rules ensure the safe use of these types. Other types declared as `ref struct` include . @@ -199,7 +228,7 @@ types. - You cannot declare `ref struct` local variables in iterators. - You cannot capture `ref struct` variables in lambda expressions or local functions. -These restrictions ensure that you do not accidentally use a `ref struct` +These restrictions ensure you do not accidentally use a `ref struct` in a manner that could promote it to the managed heap. ## `readonly ref struct` type diff --git a/samples/csharp/reference-semantics/Program.cs b/samples/csharp/reference-semantics/Program.cs index bae440934250c..5ea8fcd9fa7cd 100644 --- a/samples/csharp/reference-semantics/Program.cs +++ b/samples/csharp/reference-semantics/Program.cs @@ -12,17 +12,34 @@ static void Main(string[] args) #region UseInArgument var distance = CalculateDistance(pt1, pt2); var fromOrigin = CalculateDistance(pt1, new Point3D()); -#endregion - fromOrigin = CalculateDistance2(pt1); + #endregion + + #region ExplicitInArgument + distance = CalculateDistance(in pt1, in pt2); + distance = CalculateDistance(in pt1, new Point3D()); + distance = CalculateDistance(pt1, in Point3D.Origin); + #endregion + fromOrigin = CalculateDistance2(pt1); -#region AssignRefReadonly + #region AssignRefReadonly var originValue = Point3D.Origin; ref readonly var originReference = ref Point3D.Origin; #endregion } -#region InArgument + #region ByValue + private static double CalculateDistance(Point3D point1, Point3D point2) + { + double xDifference = point1.X - point2.X; + double yDifference = point1.Y - point2.Y; + double zDifference = point1.Z - point2.Z; + + return Math.Sqrt(xDifference * xDifference + yDifference * yDifference + zDifference * zDifference); + } + #endregion + + #region InArgument private static double CalculateDistance(in Point3D point1, in Point3D point2) { double xDifference = point1.X - point2.X;