From 5647b2181f4ecb195dfeaae4b3314d36340346fa Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 15 Mar 2018 17:31:58 -0400 Subject: [PATCH 1/8] update for new tiebreaker rules Fixes #3949 Update the locations where `in` and by value tiebreaker rules have changed. --- .../keywords/in-parameter-modifier.md | 88 +++++++++++++++---- docs/csharp/language-reference/keywords/in.md | 2 +- .../keywords/method-parameters.md | 8 +- .../csharp/language-reference/keywords/out.md | 2 +- .../reference-semantics-with-value-types.md | 26 +++++- samples/csharp/reference-semantics/Program.cs | 25 +++++- 6 files changed, 120 insertions(+), 31 deletions(-) diff --git a/docs/csharp/language-reference/keywords/in-parameter-modifier.md b/docs/csharp/language-reference/keywords/in-parameter-modifier.md index 7b425dd268c70..12f091ae5282c 100644 --- a/docs/csharp/language-reference/keywords/in-parameter-modifier.md +++ b/docs/csharp/language-reference/keywords/in-parameter-modifier.md @@ -18,7 +18,7 @@ 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 that 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. @@ -37,36 +37,90 @@ 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. - +## Overload resolution rules + +You can most easily understand the overload resolution rules for methods with by value vs. `in` arguments like the previous example methods through understanding the motivation for `in` arguments. Defining methodss 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 because the `in` modifier does not allow the value of the argument to be modified. You would explicitly add the `in` modifier at the callsite 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 selection of a method defined with a matching `in` argument. 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, properties or other expressions. Omitting `in` at the callsite informs the compiler that you will allow the compiler to create a temporary variable to pass by read only reference to the method. Enabling the compiler to create a temporary has several implications: + +- You can pass compile time constants as `in` parameters. +- You can pass properties, or other expressions expressions for `in` parameters. +- You can pass arguments where there is an implicit conversion from the argument to the parameter type. + +The following code illustrates these rules using this method: + +```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` +``` + +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, creates a temporary int with the value 0 +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 argument. + +> [!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](../../../csharp/language-reference/keywords/async.md) modifier. - -- Iterator methods, which include a [yield return](../../../csharp/language-reference/keywords/yield.md) or `yield break` statement. - -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. +- 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. -> [!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`. ## 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..1b1d28ae607bc 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) specifiese 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..36511f0f6d5b3 100644 --- a/docs/csharp/reference-semantics-with-value-types.md +++ b/docs/csharp/reference-semantics-with-value-types.md @@ -35,7 +35,7 @@ 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 @@ -89,9 +89,22 @@ 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 +an `in` parameter to any method using the `ref` or `out` modifier. +The compiler enforces that the `in` argument is a readonly variable. + +The use of `in` parameters is to avoid the potential performance costs +of 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 readonly +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 @@ -99,6 +112,11 @@ values for any `in` parameter. The follow code uses that to specify the origin [!code-csharp[InArgumentDefault](../../samples/csharp/reference-semantics/Program.cs#InArgumentDefault "Specifying defaults for an in parameter")] +To force the compiler to pass readonly arguments by reference, specify the `in` modifer +on the arguments at the callsite, as shown in the following code: + +[!code-csharp[UseInArgument](../../samples/csharp/reference-semantics/Program.cs#ExplicitInArgument "Specifying an In argument")] + 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. 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; From 3005ef06b934a68ed4d91911a5f0226e778dc257 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 16 Mar 2018 16:12:28 -0400 Subject: [PATCH 2/8] respond to feedback --- .../keywords/in-parameter-modifier.md | 14 +++--- .../reference-semantics-with-value-types.md | 44 ++++++++++--------- 2 files changed, 31 insertions(+), 27 deletions(-) diff --git a/docs/csharp/language-reference/keywords/in-parameter-modifier.md b/docs/csharp/language-reference/keywords/in-parameter-modifier.md index 12f091ae5282c..37b7b9d1646bb 100644 --- a/docs/csharp/language-reference/keywords/in-parameter-modifier.md +++ b/docs/csharp/language-reference/keywords/in-parameter-modifier.md @@ -18,7 +18,7 @@ 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 usually 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. @@ -49,16 +49,16 @@ class InOverloads ## Overload resolution rules -You can most easily understand the overload resolution rules for methods with by value vs. `in` arguments like the previous example methods through understanding the motivation for `in` arguments. Defining methodss 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. +You can most 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 because the `in` modifier does not allow the value of the argument to be modified. You would explicitly add the `in` modifier at the callsite to ensure the argument is passed by reference, not by value. Explicitly using `in` has two effects: +Specifying `in` on arguments at the call site is typically optional because the `in` modifier doesn't allow the value of the argument to be modified. You would explicitly add the `in` modifier at the callsite 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 selection of a method defined with a matching `in` argument. Otherwise, when two methods differ only in the presence of `in`, the by value overload is a better match. +First, specifying `in` at the call site forces selection of 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, properties or other expressions. Omitting `in` at the callsite informs the compiler that you will allow the compiler to create a temporary variable to pass by read only reference to the method. Enabling the compiler to create a temporary has several implications: +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. Omitting `in` at the callsite informs the compiler that you will allow the compiler to create a temporary variable to pass by read-only reference to the method. Enabling the compiler to create a temporary has several implications: -- You can pass compile time constants as `in` parameters. -- You can pass properties, or other expressions expressions for `in` parameters. +- You can pass compile-time constants as `in` parameters. +- You can pass properties, or other expressions for `in` parameters. - You can pass arguments where there is an implicit conversion from the argument to the parameter type. The following code illustrates these rules using this method: diff --git a/docs/csharp/reference-semantics-with-value-types.md b/docs/csharp/reference-semantics-with-value-types.md index 36511f0f6d5b3..09352752b2c35 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 @@ -38,14 +38,14 @@ You can use either "7.2" or "latest" for the value. ## 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 +and `out` keywords to pass arguments +by reference. The `in` keyword specifies passing the parameter by reference and the called method does not modify -the value passed to it. +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. 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 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,9 +88,13 @@ 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 +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. -The compiler enforces that the `in` argument is a readonly variable. +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 the `in` argument and its `struct` members are readonly variables. The use of `in` parameters is to avoid the potential performance costs of copies. It does not change the semantics of any method call. Therefore, @@ -129,7 +133,7 @@ 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. @@ -156,7 +160,7 @@ variable, or a by-value copy of the readonly reference: 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 @@ -190,7 +194,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 different 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 @@ -203,7 +207,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 . @@ -217,7 +221,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 From e83b496bd635720374c3454eaa2c7a7d148198ca Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 16 Mar 2018 17:00:50 -0400 Subject: [PATCH 3/8] remove one more word I intended that on the previous commit, but missed it. --- .../csharp/language-reference/keywords/in-parameter-modifier.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/csharp/language-reference/keywords/in-parameter-modifier.md b/docs/csharp/language-reference/keywords/in-parameter-modifier.md index 37b7b9d1646bb..2eb2e050e9d56 100644 --- a/docs/csharp/language-reference/keywords/in-parameter-modifier.md +++ b/docs/csharp/language-reference/keywords/in-parameter-modifier.md @@ -49,7 +49,7 @@ class InOverloads ## Overload resolution rules -You can most 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. +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 because the `in` modifier doesn't allow the value of the argument to be modified. You would explicitly add the `in` modifier at the callsite to ensure the argument is passed by reference, not by value. Explicitly using `in` has two effects: From c48017bf5d3fa53501c1da5b5ac0175de83ca47c Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Sun, 18 Mar 2018 17:59:06 -0400 Subject: [PATCH 4/8] more feedback --- .../language-reference/keywords/method-parameters.md | 2 +- docs/csharp/reference-semantics-with-value-types.md | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/csharp/language-reference/keywords/method-parameters.md b/docs/csharp/language-reference/keywords/method-parameters.md index 1b1d28ae607bc..ec529b9803fa3 100644 --- a/docs/csharp/language-reference/keywords/method-parameters.md +++ b/docs/csharp/language-reference/keywords/method-parameters.md @@ -26,7 +26,7 @@ Parameters declared for a method without [in](../../../csharp/language-reference - [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) specifiese that this parameter is passed by reference, and is written by the called method. +- [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/reference-semantics-with-value-types.md b/docs/csharp/reference-semantics-with-value-types.md index 09352752b2c35..83fe431c813e3 100644 --- a/docs/csharp/reference-semantics-with-value-types.md +++ b/docs/csharp/reference-semantics-with-value-types.md @@ -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 @@ -94,7 +94,8 @@ 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 the `in` argument and its `struct` members are readonly variables. +The compiler enforces that `struct` types passed as `in` arguments and their +`struct` members are readonly variables. The use of `in` parameters is to avoid the potential performance costs of copies. It does not change the semantics of any method call. Therefore, @@ -111,7 +112,7 @@ 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 uses that to specify 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")] From 0e679f31b3e72d0ea8f0876244abb3f9bdaf7f95 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Sun, 18 Mar 2018 18:01:03 -0400 Subject: [PATCH 5/8] one more clarification --- .../csharp/language-reference/keywords/in-parameter-modifier.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/csharp/language-reference/keywords/in-parameter-modifier.md b/docs/csharp/language-reference/keywords/in-parameter-modifier.md index 2eb2e050e9d56..f8e559df91449 100644 --- a/docs/csharp/language-reference/keywords/in-parameter-modifier.md +++ b/docs/csharp/language-reference/keywords/in-parameter-modifier.md @@ -95,7 +95,7 @@ static void Method(in int argument) 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, creates a temporary int with the value 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 From 00d294616308be17cf0ffe40519bb09c0fda75f6 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Wed, 21 Mar 2018 13:19:29 -0400 Subject: [PATCH 6/8] feedback mostly addressed Revisit after merging #4770 for one final comment. --- .../keywords/in-parameter-modifier.md | 22 +++++++------ .../keywords/method-parameters.md | 6 ++-- .../reference-semantics-with-value-types.md | 31 +++++++++---------- 3 files changed, 30 insertions(+), 29 deletions(-) diff --git a/docs/csharp/language-reference/keywords/in-parameter-modifier.md b/docs/csharp/language-reference/keywords/in-parameter-modifier.md index f8e559df91449..ec8b688abd39d 100644 --- a/docs/csharp/language-reference/keywords/in-parameter-modifier.md +++ b/docs/csharp/language-reference/keywords/in-parameter-modifier.md @@ -21,7 +21,7 @@ The `in` keyword causes arguments to be passed by reference. It is like the [ref 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. @@ -51,17 +51,19 @@ class InOverloads 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 because the `in` modifier doesn't allow the value of the argument to be modified. You would explicitly add the `in` modifier at the callsite to ensure the argument is passed by reference, not by value. Explicitly using `in` has two effects: +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 selection of 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. +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. Omitting `in` at the callsite informs the compiler that you will allow the compiler to create a temporary variable to pass by read-only reference to the method. Enabling the compiler to create a temporary has several implications: +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. Omitting `in` at the call site informs the compiler that you will allow the compiler 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 can pass compile-time constants as `in` parameters. -- You can pass properties, or other expressions for `in` parameters. -- You can pass arguments where there is an implicit conversion from the argument to the parameter type. +- 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. -The following code illustrates these rules using this method: +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) @@ -79,7 +81,7 @@ Method(i); // passed by readonly reference Method(in i); // passed by readonly reference, explicitly using `in` ``` -Now, suppose another method using by value arguments was available, the results change as shown in the following code: +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) @@ -102,7 +104,7 @@ 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 argument. +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. diff --git a/docs/csharp/language-reference/keywords/method-parameters.md b/docs/csharp/language-reference/keywords/method-parameters.md index ec529b9803fa3..df45dcb45ec42 100644 --- a/docs/csharp/language-reference/keywords/method-parameters.md +++ b/docs/csharp/language-reference/keywords/method-parameters.md @@ -22,11 +22,11 @@ Parameters declared for a method without [in](../../../csharp/language-reference - [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) specifies that this parameter is passed by reference, but is only read by the called method. +- [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) specifies that this parameter is passed by reference, and may be read or written by the called method. +- [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) specifies that this parameter is passed by reference, and is written by the called method. +- [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/reference-semantics-with-value-types.md b/docs/csharp/reference-semantics-with-value-types.md index 83fe431c813e3..fa7df43244b1b 100644 --- a/docs/csharp/reference-semantics-with-value-types.md +++ b/docs/csharp/reference-semantics-with-value-types.md @@ -40,12 +40,12 @@ You can use either "7.2" or "latest" for the value. C# 7.2 adds the `in` keyword to complement the existing `ref` and `out` keywords to pass arguments by reference. The `in` keyword specifies passing -the parameter by reference and the called method does not modify +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 don't -specify any of the following modifiers. Each of these modifiers specifies +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: @@ -90,15 +90,15 @@ 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 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 +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 readonly variables. +`struct` members are read only variables. -The use of `in` parameters is to avoid the potential performance costs -of copies. It does not change the semantics of any method call. Therefore, +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: @@ -107,23 +107,22 @@ allowed to make a copy of the argument for the following reasons: - 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 readonly +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 following 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")] -To force the compiler to pass readonly arguments by reference, specify the `in` modifer -on the arguments at the callsite, as shown in the following code: +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")] -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. +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 @@ -137,7 +136,7 @@ The compiler enforces that the caller cannot modify the reference. Attempts 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. +defensive copy. <> It's likely that the library using `Point3D` would often use the origin throughout the code. Every instance creates a new object on the stack. It may @@ -154,7 +153,7 @@ 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")] @@ -167,7 +166,7 @@ can't be modified. Attempts to do so result in a compile-time error. 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. @@ -195,7 +194,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 implemented a bit different 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 From d97ac0b988c112e4f8318844706aa3067d4583b9 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 22 Mar 2018 11:14:10 -0400 Subject: [PATCH 7/8] rebase and address remaining feedback. --- .../keywords/in-parameter-modifier.md | 1 - .../reference-semantics-with-value-types.md | 15 +++++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/csharp/language-reference/keywords/in-parameter-modifier.md b/docs/csharp/language-reference/keywords/in-parameter-modifier.md index ec8b688abd39d..0a5a29b355643 100644 --- a/docs/csharp/language-reference/keywords/in-parameter-modifier.md +++ b/docs/csharp/language-reference/keywords/in-parameter-modifier.md @@ -116,7 +116,6 @@ You can't use the `in`, `ref`, and `out` keywords for the following kinds of met - 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)] diff --git a/docs/csharp/reference-semantics-with-value-types.md b/docs/csharp/reference-semantics-with-value-types.md index fa7df43244b1b..81c4c8dd349a6 100644 --- a/docs/csharp/reference-semantics-with-value-types.md +++ b/docs/csharp/reference-semantics-with-value-types.md @@ -93,9 +93,9 @@ 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`. +of member access are `structs`. The compiler enforces that `struct` types passed as `in` arguments and their -`struct` members are read only variables. +`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, @@ -122,6 +122,12 @@ 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 @@ -133,10 +139,11 @@ 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 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. <> +defensive copy. It's likely that the library using `Point3D` would often use the origin throughout the code. Every instance creates a new object on the stack. It may From f2046f7462d89f3a97d4775fe3005c620945e91d Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 23 Mar 2018 12:18:31 -0400 Subject: [PATCH 8/8] finsl review comments. --- .../keywords/in-parameter-modifier.md | 2 +- docs/csharp/reference-semantics-with-value-types.md | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/csharp/language-reference/keywords/in-parameter-modifier.md b/docs/csharp/language-reference/keywords/in-parameter-modifier.md index 0a5a29b355643..c9bfc04f37fa3 100644 --- a/docs/csharp/language-reference/keywords/in-parameter-modifier.md +++ b/docs/csharp/language-reference/keywords/in-parameter-modifier.md @@ -55,7 +55,7 @@ Specifying `in` on arguments at the call site is typically optional. There is no 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. Omitting `in` at the call site informs the compiler that you will allow the compiler 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: +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: - A temporary variable allows compile-time constants as `in` parameters. - A temporary variable allows properties, or other expressions for `in` parameters. diff --git a/docs/csharp/reference-semantics-with-value-types.md b/docs/csharp/reference-semantics-with-value-types.md index 81c4c8dd349a6..0e5df4304a8a9 100644 --- a/docs/csharp/reference-semantics-with-value-types.md +++ b/docs/csharp/reference-semantics-with-value-types.md @@ -40,7 +40,7 @@ You can use either "7.2" or "latest" for the value. C# 7.2 adds the `in` keyword to complement the existing `ref` 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 argument by reference, but the called method does not modify the value. This addition provides a full vocabulary to express your design intent. @@ -95,7 +95,7 @@ field is a `struct` type and the parameter is also a `struct` type. In fact, the 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. +`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, @@ -107,7 +107,7 @@ allowed to make a copy of the argument for the following reasons: - 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 +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 @@ -160,7 +160,7 @@ 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 read only 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")] @@ -173,7 +173,7 @@ can't be modified. Attempts to do so result in a compile-time error. 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 read only 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.