From 850af143e31b812db8064a8e3dcb2c50e1f351dd Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 9 Feb 2026 16:46:05 -0800 Subject: [PATCH 1/7] Checkpoint from Copilot CLI for coding agent session --- ...ction-emit-dynamicmethod-createdelegate.md | 53 ++++++++++++ ...stem-reflection-emit-dynamicmethod-ctor.md | 81 +++++++++++++++++++ ...tion-emit-dynamicmethod-defineparameter.md | 20 +++++ ...ction-emit-dynamicmethod-getilgenerator.md | 37 +++++++++ ...em-reflection-emit-dynamicmethod-invoke.md | 31 +++++++ ...n-emit-dynamicmethod-issecuritycritical.md | 41 ++++++++++ ...it-dynamicmethod-issecuritysafecritical.md | 41 ++++++++++ ...mit-dynamicmethod-issecuritytransparent.md | 41 ++++++++++ ...stem-reflection-emit-dynamicmethod-name.md | 19 +++++ 9 files changed, 364 insertions(+) create mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md create mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md create mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-defineparameter.md create mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md create mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md create mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md create mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritysafecritical.md create mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritytransparent.md create mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-name.md diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md new file mode 100644 index 0000000000000..73b97a9bb51db --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md @@ -0,0 +1,53 @@ +--- +title: System.Reflection.Emit.DynamicMethod.CreateDelegate methods +description: Learn about the System.Reflection.Emit.DynamicMethod.CreateDelegate methods. +ms.date: 02/10/2026 +ai-usage: ai-assisted +--- +# System.Reflection.Emit.DynamicMethod.CreateDelegate methods + +[!INCLUDE [context](includes/context.md)] + +## + +Calling the method or the method completes the dynamic method. Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown. + +To create a method body for a dynamic method when you have your own MSIL generator, call the method to obtain a object. If you don't have your own MSIL generator, call the method to obtain an object that can be used to generate the method body. + +### Examples + +The following code example creates a dynamic method that takes two parameters. The example emits a simple function body that prints the first parameter to the console, and the example uses the second parameter as the return value of the method. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the method. + +:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/.ctor/source1.cs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/.ctor/source1.vb" id="Snippet1"::: + +## + +This method overload creates a delegate bound to a particular object. Such a delegate is said to be closed over its first argument. Although the method is static, it acts as if it were an instance method; the instance is `target`. + +This method overload requires `target` to be of the same type as the first parameter of the dynamic method, or to be assignable to that type (for example, a derived class). The signature of `delegateType` has all the parameters of the dynamic method except the first. For example, if the dynamic method has the parameters , , and , then `delegateType` has the parameters and ; `target` is of type . + +Calling the method or the method completes the dynamic method. Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown. + +To create a method body for a dynamic method when you have your own MSIL generator, call the method to obtain a object. If you don't have your own MSIL generator, call the method to obtain an object that can be used to generate the method body. + +### Examples + +The following code example creates a delegate that binds a to an instance of a type, so that the method acts on the same instance each time it's invoked. + +The code example defines a class named `Example` with a private field, a class named `DerivedFromExample` that derives from the first class, a delegate type named `UseLikeStatic` that returns and has parameters of type `Example` and , and a delegate type named `UseLikeInstance` that returns and has one parameter of type . + +The example code then creates a that changes the private field of an instance of `Example` and returns the previous value. + +> [!NOTE] +> In general, changing the internal fields of classes isn't good object-oriented coding practice. + +The example code creates an instance of `Example` and then creates two delegates. The first is of type `UseLikeStatic`, which has the same parameters as the dynamic method. The second is of type `UseLikeInstance`, which lacks the first parameter (of type `Example`). This delegate is created using the method overload; the second parameter of that method overload is an instance of `Example`, in this case the instance just created, which is bound to the newly created delegate. Whenever that delegate is invoked, the dynamic method acts on the bound instance of `Example`. + +> [!NOTE] +> This is an example of the relaxed rules for delegate binding introduced in .NET Framework 2.0, along with new overloads of the method. For more information, see the class. + +The `UseLikeStatic` delegate is invoked, passing in the instance of `Example` that's bound to the `UseLikeInstance` delegate. Then the `UseLikeInstance` delegate is invoked, so that both delegates act on the same instance of `Example`. The changes in the values of the internal field are displayed after each call. Finally, a `UseLikeInstance` delegate is bound to an instance of `DerivedFromExample`, and the delegate calls are repeated. + +:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/.ctor/source.cs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/.ctor/source.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md new file mode 100644 index 0000000000000..52d4369258275 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md @@ -0,0 +1,81 @@ +--- +title: System.Reflection.Emit.DynamicMethod constructors +description: Learn about the System.Reflection.Emit.DynamicMethod constructors. +ms.date: 02/10/2026 +ai-usage: ai-assisted +--- +# System.Reflection.Emit.DynamicMethod constructors + +[!INCLUDE [context](includes/context.md)] + +## constructor + +The dynamic method that is created by this constructor is associated with an anonymous assembly instead of an existing type or module. The anonymous assembly exists only to provide a sandbox environment for dynamic methods, that is, to isolate them from other code. This environment makes it safe for the dynamic method to be emitted and executed by partially trusted code. + +Anonymously hosted dynamic methods don't have automatic access to any types or members that are `private`, `protected`, or `internal` (`Friend` in Visual Basic). This is different from dynamic methods that are associated with an existing type or module, which have access to hidden members in their associated scope. + +Specify `true` for `restrictedSkipVisibility` if your dynamic method has to access types or members that are `private`, `protected`, or `internal`. This gives the dynamic method restricted access to these members. That is, the members can be accessed only if the following conditions are met: + +- The target members belong to an assembly that has a level of trust equal to or lower than the call stack that emits the dynamic method. + +- The call stack that emits the dynamic method is granted with the flag. This is always true when the code is executed with full trust. For partially trusted code, it's true only if the host explicitly grants the permission. + + > [!IMPORTANT] + > If the permission hasn't been granted, a security exception is thrown when is called or when the dynamic method is invoked, not when this constructor is called. No special permissions are required to emit the dynamic method. + +For example, a dynamic method that's created with `restrictedSkipVisibility` set to `true` can access a private member of any assembly on the call stack if the call stack has been granted restricted member access. If the dynamic method is created with partially trusted code on the call stack, it can't access a private member of a type in a .NET Framework assembly, because such assemblies are fully trusted. + +If `restrictedSkipVisibility` is `false`, JIT visibility checks are enforced. The code in the dynamic method has access to public methods of public classes, and exceptions are thrown if it tries to access types or members that are `private`, `protected`, or `internal`. + +When an anonymously hosted dynamic method is constructed, the call stack of the emitting assembly is included. When the method is invoked, the permissions of the emitting call stack are used instead of the permissions of the actual caller. Thus, the dynamic method can't execute at a higher level of privilege than that of the assembly that emitted it, even if it's passed to and executed by an assembly that has a higher trust level. + +This constructor specifies the method attributes and , and the calling convention . + +> [!NOTE] +> This constructor was introduced in .NET Framework 3.5 or later. + +## constructor + +This constructor specifies method attributes and , calling convention , and doesn't skip just-in-time (JIT) visibility checks. + +The dynamic method created with this constructor has access to public and `internal` (`Friend` in Visual Basic) members of all the types contained in module `m`. + +> [!NOTE] +> For backward compatibility, this constructor demands with the flag if the following conditions are both true: `m` is a module other than the calling module, and the demand for with the flag has failed. If the demand for succeeds, the operation is allowed. + +### Examples + +The following code example creates a dynamic method that takes two parameters. The example emits a simple function body that prints the first parameter to the console, and the example uses the second parameter as the return value of the method. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the method. + +:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/.ctor/source1.cs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/.ctor/source1.vb" id="Snippet1"::: + +## constructor + +The dynamic method created with this constructor has access to all members of the type `owner`, and to public and `internal` (`Friend` in Visual Basic) members of all the other types in the module that contains `owner`. + +This constructor specifies method attributes and , calling convention , and doesn't skip just-in-time (JIT) visibility checks. + +> [!NOTE] +> For backward compatibility, this constructor demands with the flag if the following conditions are both true: `owner` is in a module other than the calling module, and the demand for with the flag has failed. If the demand for succeeds, the operation is allowed. + +### Examples + +The following code example creates a that's logically associated with a type. This association gives it access to the private members of that type. + +The code example defines a class named `Example` with a private field, a class named `DerivedFromExample` that derives from the first class, a delegate type named `UseLikeStatic` that returns and has parameters of type `Example` and , and a delegate type named `UseLikeInstance` that returns and has one parameter of type . + +The example code then creates a that changes the private field of an instance of `Example` and returns the previous value. + +> [!NOTE] +> In general, changing the internal fields of classes isn't good object-oriented coding practice. + +The example code creates an instance of `Example` and then creates two delegates. The first is of type `UseLikeStatic`, which has the same parameters as the dynamic method. The second is of type `UseLikeInstance`, which lacks the first parameter (of type `Example`). This delegate is created using the method overload; the second parameter of that method overload is an instance of `Example`, in this case the instance just created, which is bound to the newly created delegate. Whenever that delegate is invoked, the dynamic method acts on the bound instance of `Example`. + +> [!NOTE] +> This is an example of the relaxed rules for delegate binding introduced in .NET Framework 2.0, along with new overloads of the method. For more information, see the class. + +The `UseLikeStatic` delegate is invoked, passing in the instance of `Example` that's bound to the `UseLikeInstance` delegate. Then the `UseLikeInstance` delegate is invoked, so that both delegates act on the same instance of `Example`. The changes in the values of the internal field are displayed after each call. Finally, a `UseLikeInstance` delegate is bound to an instance of `DerivedFromExample`, and the delegate calls are repeated. + +:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/.ctor/source.cs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/.ctor/source.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-defineparameter.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-defineparameter.md new file mode 100644 index 0000000000000..aa615217e02a8 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-defineparameter.md @@ -0,0 +1,20 @@ +--- +title: System.Reflection.Emit.DynamicMethod.DefineParameter method +description: Learn about the System.Reflection.Emit.DynamicMethod.DefineParameter method. +ms.date: 02/10/2026 +ai-usage: ai-assisted +--- +# System.Reflection.Emit.DynamicMethod.DefineParameter method + +[!INCLUDE [context](includes/context.md)] + +If `position` is 0, the method refers to the return value. Setting parameter information has no effect on the return value. + +If the dynamic method has already been completed, by calling the or method, the method has no effect. No exception is thrown. + +## Examples + +The following code example shows how to define parameter information for a dynamic method. This code example is part of a larger example provided for the class. + +:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/Overview/source.cs" id="Snippet33"::: +:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/Overview/source.vb" id="Snippet33"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md new file mode 100644 index 0000000000000..cd3f38a6b613e --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md @@ -0,0 +1,37 @@ +--- +title: System.Reflection.Emit.DynamicMethod.GetILGenerator methods +description: Learn about the System.Reflection.Emit.DynamicMethod.GetILGenerator methods. +ms.date: 02/10/2026 +ai-usage: ai-assisted +--- +# System.Reflection.Emit.DynamicMethod.GetILGenerator methods + +[!INCLUDE [context](includes/context.md)] + +## + +After a dynamic method has been completed, by calling the or method, any further attempt to add MSIL is ignored. No exception is thrown. + +> [!NOTE] +> There are restrictions on unverifiable code in dynamic methods, even in some full-trust scenarios. See the "Verification" section in Remarks for . + +### Examples + +The following code example creates a dynamic method that takes two parameters. The example emits a simple function body that prints the first parameter to the console, and the example uses the second parameter as the return value of the method. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the method. + +:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/.ctor/source1.cs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/.ctor/source1.vb" id="Snippet1"::: + +## + +After a dynamic method has been completed, by calling the or method, any further attempt to add MSIL is ignored. No exception is thrown. + +> [!NOTE] +> There are restrictions on unverifiable code in dynamic methods, even in some full-trust scenarios. See the "Verification" section in Remarks for . + +### Examples + +The following code example demonstrates this method overload. This code example is part of a larger example provided for the class. + +:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/Overview/source.cs" id="Snippet2"::: +:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/Overview/source.vb" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md new file mode 100644 index 0000000000000..9202c64d1c51a --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md @@ -0,0 +1,31 @@ +--- +title: System.Reflection.Emit.DynamicMethod.Invoke method +description: Learn about the System.Reflection.Emit.DynamicMethod.Invoke method. +ms.date: 02/10/2026 +ai-usage: ai-assisted +--- +# System.Reflection.Emit.DynamicMethod.Invoke method + +[!INCLUDE [context](includes/context.md)] + +In addition to the listed exceptions, the calling code should be prepared to catch any exceptions thrown by the dynamic method. + +Executing a dynamic method with a delegate created by the method is more efficient than executing it with the method. + +Calling the method or the method completes the dynamic method. Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown. + +All dynamic methods are static, so the `obj` parameter is always ignored. To treat a dynamic method as if it were an instance method, use the overload that takes an object instance. + +If the dynamic method has no parameters, the value of `parameters` should be `null`. Otherwise the number, type, and order of elements in the parameters array should be identical to the number, type, and order of parameters of the dynamic method. + +> [!NOTE] +> This method overload is called by the method overload inherited from the class, so the preceding remarks apply to both overloads. + +This method doesn't demand permissions directly, but invoking the dynamic method can result in security demands, depending on the method. For example, no demands are made for anonymously hosted dynamic methods that are created with the `restrictedSkipVisibility` parameter set to `false`. On the other hand, if you create a method with `restrictedSkipVisibility` set to `true` so it can access a hidden member of a target assembly, the method causes a demand for the permissions of the target assembly plus with the flag. + +## Examples + +The following code example invokes a dynamic method with exact binding, using the US-English culture. This code example is part of a larger example provided for the class. + +:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/Overview/source.cs" id="Snippet4"::: +:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/Overview/source.vb" id="Snippet4"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md new file mode 100644 index 0000000000000..6bae05b6ff73d --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md @@ -0,0 +1,41 @@ +--- +title: System.Reflection.Emit.DynamicMethod.IsSecurityCritical property +description: Learn about the System.Reflection.Emit.DynamicMethod.IsSecurityCritical property. +ms.date: 02/10/2026 +ai-usage: ai-assisted +--- +# System.Reflection.Emit.DynamicMethod.IsSecurityCritical property + +[!INCLUDE [context](includes/context.md)] + +The , , and properties report the transparency level of the dynamic method as determined by the common language runtime (CLR). The combinations of these properties are shown in the following table: + +| Security level | IsSecurityCritical | IsSecuritySafeCritical | IsSecurityTransparent | +|----------------|--------------------|-----------------------|-----------------------| +| Critical | `true` | `false` | `false` | +| Safe critical | `true` | `true` | `false` | +| Transparent | `false` | `false` | `true` | + +Using these properties is much simpler than examining the security annotations of an assembly and its types, checking the current trust level, and attempting to duplicate the runtime's rules. + +The transparency of a dynamic method depends on the module it's associated with. If the dynamic method is associated with a type rather than a module, its transparency depends on the module that contains the type. Dynamic methods don't have security annotations, so they're assigned the default transparency for the associated module. + +- Anonymously hosted dynamic methods are always transparent, because the system-provided module that contains them is transparent. + +- The transparency of a dynamic method that's associated with a trusted assembly (that is, a strong-named assembly that's installed in the global assembly cache) is described in the following table. + + | Assembly annotation | Level 1 transparency | Level 2 transparency | + |---------------------|----------------------|----------------------| + | Fully transparent | Transparent | Transparent | + | Fully critical | Critical | Critical | + | Mixed transparency | Transparent | Transparent | + | Security-agnostic | Safe-critical | Critical | + + For example, if you associate a dynamic method with a type that's in mscorlib.dll, which has level 2 mixed transparency, the dynamic method is transparent and can't execute critical code. For information about transparency levels, see [Security-Transparent Code, Level 1](/dotnet/framework/misc/security-transparent-code-level-1) and [Security-Transparent Code, Level 2](/dotnet/framework/misc/security-transparent-code-level-2). + + > [!NOTE] + > Associating a dynamic method with a module in a trusted level 1 assembly that's security-agnostic, such as System.dll, doesn't permit elevation of trust. If the grant set of the code that calls the dynamic method doesn't include the grant set of System.dll (that is, full trust), is thrown when the dynamic method is called. + +- The transparency of a dynamic method that's associated with a partially trusted assembly depends on how the assembly is loaded. If the assembly is loaded with partial trust (for example, into a sandboxed application domain), the runtime ignores the security annotations of the assembly. The assembly and all its types and members, including dynamic methods, are treated as transparent. The runtime pays attention to security annotations only if the partial-trust assembly is loaded with full trust (for example, into the default application domain of a desktop application). In that case, the runtime assigns the dynamic method the default transparency for methods according to the assembly's annotations. + +For more information about reflection emit and transparency, see [Security Issues in Reflection Emit](/dotnet/framework/reflection-and-codedom/security-issues-in-reflection-emit). For information about transparency, see [Security Changes](/dotnet/framework/security/security-changes). diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritysafecritical.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritysafecritical.md new file mode 100644 index 0000000000000..31e9004707e43 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritysafecritical.md @@ -0,0 +1,41 @@ +--- +title: System.Reflection.Emit.DynamicMethod.IsSecuritySafeCritical property +description: Learn about the System.Reflection.Emit.DynamicMethod.IsSecuritySafeCritical property. +ms.date: 02/10/2026 +ai-usage: ai-assisted +--- +# System.Reflection.Emit.DynamicMethod.IsSecuritySafeCritical property + +[!INCLUDE [context](includes/context.md)] + +The , , and properties report the transparency level of the dynamic method as determined by the common language runtime (CLR). The combinations of these properties are shown in the following table: + +| Security level | IsSecurityCritical | IsSecuritySafeCritical | IsSecurityTransparent | +|----------------|--------------------|-----------------------|-----------------------| +| Critical | `true` | `false` | `false` | +| Safe critical | `true` | `true` | `false` | +| Transparent | `false` | `false` | `true` | + +Using these properties is much simpler than examining the security annotations of an assembly and its types, checking the current trust level, and attempting to duplicate the runtime's rules. + +The transparency of a dynamic method depends on the module it's associated with. If the dynamic method is associated with a type rather than a module, its transparency depends on the module that contains the type. Dynamic methods don't have security annotations, so they're assigned the default transparency for the associated module. + +- Anonymously hosted dynamic methods are always transparent, because the system-provided module that contains them is transparent. + +- The transparency of a dynamic method that's associated with a trusted assembly (that is, a strong-named assembly that's installed in the global assembly cache) is described in the following table. + + | Assembly annotation | Level 1 transparency | Level 2 transparency | + |---------------------|----------------------|----------------------| + | Fully transparent | Transparent | Transparent | + | Fully critical | Critical | Critical | + | Mixed transparency | Transparent | Transparent | + | Security-agnostic | Safe-critical | Critical | + + For example, if you associate a dynamic method with a type that's in mscorlib.dll, which has level 2 mixed transparency, the dynamic method is transparent and can't execute critical code. For information about transparency levels, see [Security-Transparent Code, Level 1](/dotnet/framework/misc/security-transparent-code-level-1) and [Security-Transparent Code, Level 2](/dotnet/framework/misc/security-transparent-code-level-2). + + > [!NOTE] + > Associating a dynamic method with a module in a trusted level 1 assembly that's security-agnostic, such as System.dll, doesn't permit elevation of trust. If the grant set of the code that calls the dynamic method doesn't include the grant set of System.dll (that is, full trust), is thrown when the dynamic method is called. + +- The transparency of a dynamic method that's associated with a partially trusted assembly depends on how the assembly is loaded. If the assembly is loaded with partial trust (for example, into a sandboxed application domain), the runtime ignores the security annotations of the assembly. The assembly and all its types and members, including dynamic methods, are treated as transparent. The runtime pays attention to security annotations only if the partial-trust assembly is loaded with full trust (for example, into the default application domain of a desktop application). In that case, the runtime assigns the dynamic method the default transparency for methods according to the assembly's annotations. + +For more information about reflection emit and transparency, see [Security Issues in Reflection Emit](/dotnet/framework/reflection-and-codedom/security-issues-in-reflection-emit). For information about transparency, see [Security Changes](/dotnet/framework/security/security-changes). diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritytransparent.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritytransparent.md new file mode 100644 index 0000000000000..cf20060f09d53 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritytransparent.md @@ -0,0 +1,41 @@ +--- +title: System.Reflection.Emit.DynamicMethod.IsSecurityTransparent property +description: Learn about the System.Reflection.Emit.DynamicMethod.IsSecurityTransparent property. +ms.date: 02/10/2026 +ai-usage: ai-assisted +--- +# System.Reflection.Emit.DynamicMethod.IsSecurityTransparent property + +[!INCLUDE [context](includes/context.md)] + +The , , and properties report the transparency level of the dynamic method as determined by the common language runtime (CLR). The combinations of these properties are shown in the following table: + +| Security level | IsSecurityCritical | IsSecuritySafeCritical | IsSecurityTransparent | +|----------------|--------------------|-----------------------|-----------------------| +| Critical | `true` | `false` | `false` | +| Safe critical | `true` | `true` | `false` | +| Transparent | `false` | `false` | `true` | + +Using these properties is much simpler than examining the security annotations of an assembly and its types, checking the current trust level, and attempting to duplicate the runtime's rules. + +The transparency of a dynamic method depends on the module it's associated with. If the dynamic method is associated with a type rather than a module, its transparency depends on the module that contains the type. Dynamic methods don't have security annotations, so they're assigned the default transparency for the associated module. + +- Anonymously hosted dynamic methods are always transparent, because the system-provided module that contains them is transparent. + +- The transparency of a dynamic method that's associated with a trusted assembly (that is, a strong-named assembly that's installed in the global assembly cache) is described in the following table. + + | Assembly annotation | Level 1 transparency | Level 2 transparency | + |---------------------|----------------------|----------------------| + | Fully transparent | Transparent | Transparent | + | Fully critical | Critical | Critical | + | Mixed transparency | Transparent | Transparent | + | Security-agnostic | Safe-critical | Critical | + + For example, if you associate a dynamic method with a type that's in mscorlib.dll, which has level 2 mixed transparency, the dynamic method is transparent and can't execute critical code. For information about transparency levels, see [Security-Transparent Code, Level 1](/dotnet/framework/misc/security-transparent-code-level-1) and [Security-Transparent Code, Level 2](/dotnet/framework/misc/security-transparent-code-level-2). + + > [!NOTE] + > Associating a dynamic method with a module in a trusted level 1 assembly that's security-agnostic, such as System.dll, doesn't permit elevation of trust. If the grant set of the code that calls the dynamic method doesn't include the grant set of System.dll (that is, full trust), is thrown when the dynamic method is called. + +- The transparency of a dynamic method that's associated with a partially trusted assembly depends on how the assembly is loaded. If the assembly is loaded with partial trust (for example, into a sandboxed application domain), the runtime ignores the security annotations of the assembly. The assembly and all its types and members, including dynamic methods, are treated as transparent. The runtime pays attention to security annotations only if the partial-trust assembly is loaded with full trust (for example, into the default application domain of a desktop application). In that case, the runtime assigns the dynamic method the default transparency for methods according to the assembly's annotations. + +For more information about reflection emit and transparency, see [Security Issues in Reflection Emit](/dotnet/framework/reflection-and-codedom/security-issues-in-reflection-emit). For information about transparency, see [Security Changes](/dotnet/framework/security/security-changes). diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-name.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-name.md new file mode 100644 index 0000000000000..9846db7c93c33 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-name.md @@ -0,0 +1,19 @@ +--- +title: System.Reflection.Emit.DynamicMethod.Name property +description: Learn about the System.Reflection.Emit.DynamicMethod.Name property. +ms.date: 02/10/2026 +ai-usage: ai-assisted +--- +# System.Reflection.Emit.DynamicMethod.Name property + +[!INCLUDE [context](includes/context.md)] + +> [!NOTE] +> It's not necessary to name dynamic methods. + +## Examples + +The following code example displays the name of a dynamic method. This code example is part of a larger example provided for the class. + +:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/Overview/source.cs" id="Snippet27"::: +:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/Overview/source.vb" id="Snippet27"::: From 5f60692ab8c63b199f436975253c827cb9a668a0 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 9 Feb 2026 17:18:07 -0800 Subject: [PATCH 2/7] clean up xrefs --- .../runtime-libraries/includes/context.md | 3 +- .../includes/stringbuilder-perf-note.md | 8 +- .../microsoft-win32-registry.md | 2 +- .../runtime-libraries/system-appcontext.md | 8 +- .../system-appdomain-unhandledexception.md | 2 +- .../runtime-libraries/system-boolean.md | 30 ++-- .../runtime-libraries/system-byte.md | 8 +- .../runtime-libraries/system-char.md | 26 ++-- .../system-collections-generic-hashset{t}.md | 54 +++---- .../system-collections-generic-list{t}.md | 42 +++--- ...yedcollection{tkey,titem}-changeitemkey.md | 8 +- ...ons-objectmodel-observablecollection{t}.md | 14 +- .../runtime-libraries/system-console.md | 50 +++---- .../runtime-libraries/system-convert.md | 38 ++--- .../system-data-commandbehavior.md | 2 +- .../runtime-libraries/system-data-dataset.md | 14 +- .../system-data-datatable.md | 8 +- .../system-datetime-tobinary.md | 14 +- .../system-datetime-tryparse.md | 10 +- .../runtime-libraries/system-datetime.md | 54 +++---- .../runtime-libraries/system-decimal.md | 10 +- .../system-delegate-createdelegate.md | 14 +- .../system-diagnostics-tracing-eventsource.md | 2 +- ...agnostics-tracing-eventwritteneventargs.md | 4 +- .../system-double-compareto.md | 10 +- .../runtime-libraries/system-double-equals.md | 10 +- .../runtime-libraries/system-double.md | 34 ++--- .../system-drawing-drawing2d-matrix.md | 2 +- .../system-dynamic-expandoobject.md | 2 +- .../runtime-libraries/system-enum.md | 22 +-- ...stem-environment-getenvironmentvariable.md | 10 +- .../system-exception-message.md | 2 +- .../runtime-libraries/system-exception.md | 26 ++-- .../system-flagsattribute.md | 4 +- .../runtime-libraries/system-gc.md | 14 +- .../system-globalization-compareinfo.md | 10 +- .../system-globalization-compareoptions.md | 2 +- ...zation-cultureandregioninfobuilder-ctor.md | 4 +- ...obalization-cultureandregioninfobuilder.md | 22 +-- ...lobalization-cultureinfo-currentculture.md | 16 +- ...balization-cultureinfo-currentuiculture.md | 12 +- ...balization-cultureinfo-invariantculture.md | 6 +- .../system-globalization-cultureinfo.md | 68 ++++----- ...system-globalization-datetimeformatinfo.md | 138 +++++++++--------- .../system-globalization-numberformatinfo.md | 80 +++++----- .../system-globalization-persiancalendar.md | 2 +- .../system-globalization-regioninfo.md | 2 +- .../system-globalization-sortkey.md | 16 +- .../system-globalization-sortversion.md | 10 +- .../system-iasyncdisposable.md | 6 +- .../runtime-libraries/system-idisposable.md | 32 ++-- .../runtime-libraries/system-int32.md | 6 +- .../runtime-libraries/system-int64.md | 6 +- .../system-invalidcastexception.md | 8 +- .../system-invalidoperationexception.md | 70 ++++----- .../runtime-libraries/system-io-filestream.md | 12 +- .../system-io-filesystemwatcher.md | 14 +- ...ystem-linq-expressions-binaryexpression.md | 50 +++---- .../system-linq-expressions-expression-add.md | 2 +- .../system-midpointrounding.md | 2 +- .../system-net-ftpwebrequest-proxy.md | 4 +- .../system-net-http-httpclient.md | 30 ++-- .../system-net-httplistener.md | 10 +- .../system-net-sockets-socket.md | 14 +- .../system-notimplementedexception.md | 4 +- .../system-notsupportedexception.md | 10 +- .../runtime-libraries/system-nullable.md | 6 +- .../runtime-libraries/system-nullable{t}.md | 12 +- .../system-numerics-biginteger.md | 30 ++-- .../system-numerics-complex.md | 10 +- .../runtime-libraries/system-object-equals.md | 52 +++---- .../system-object-finalize.md | 38 ++--- .../system-object-gethashcode.md | 18 +-- .../system-object-tostring.md | 42 +++--- .../runtime-libraries/system-object.md | 8 +- .../runtime-libraries/system-random.md | 60 ++++---- .../system-reflection-emit-assemblybuilder.md | 10 +- .../system-reflection-emit-methodbuilder.md | 12 +- ...eflection-emit-persistedassemblybuilder.md | 6 +- .../system-reflection-emit-typebuilder.md | 12 +- ...ources-missingmanifestresourceexception.md | 8 +- .../system-resources-resourcemanager-ctor.md | 4 +- ...tem-resources-resourcemanager-getobject.md | 8 +- ...tem-resources-resourcemanager-getstring.md | 10 +- .../system-resources-resourcemanager.md | 22 +-- .../system-resources-resourcereader.md | 20 +-- ...lerservices-internalsvisibletoattribute.md | 6 +- ...ilerservices-runtimehelpers-gethashcode.md | 26 ++-- ...untime-interopservices-icustommarshaler.md | 26 ++-- ...interopservices-marshal-getactiveobject.md | 2 +- ...stem-runtime-interopservices-safehandle.md | 2 +- ...ime-serialization-datacontractattribute.md | 2 +- ...me-serialization-datacontractserializer.md | 4 +- ...ime-serialization-iextensibledataobject.md | 2 +- ...e-serialization-xsddatacontractexporter.md | 6 +- ...versioning-componentguaranteesattribute.md | 2 +- ...y-cryptography-rsacryptoserviceprovider.md | 2 +- ...tem-security-cryptography-rsaparameters.md | 4 +- ...tem-security-cryptography-xml-signedxml.md | 14 +- .../system-security-securestring.md | 44 +++--- .../system-single-compareto.md | 8 +- .../runtime-libraries/system-single-equals.md | 8 +- .../runtime-libraries/system-single.md | 22 +-- .../runtime-libraries/system-span{t}.md | 10 +- .../runtime-libraries/system-string-ctor.md | 34 ++--- .../runtime-libraries/system-string-format.md | 40 ++--- .../runtime-libraries/system-string-intern.md | 4 +- .../system-string-isnullorempty.md | 6 +- .../runtime-libraries/system-string.md | 116 +++++++-------- .../system-stringcomparer.md | 2 +- .../system-text-encoding-default.md | 2 +- .../runtime-libraries/system-text-encoding.md | 12 +- ...tem-text-regularexpressions-regex-match.md | 2 +- .../system-text-regularexpressions-regex.md | 26 ++-- .../runtime-libraries/system-text-rune.md | 44 +++--- .../system-text-stringbuilder.md | 60 ++++---- .../system-threading-monitor-wait.md | 30 ++-- .../system-threading-monitor.md | 46 +++--- .../system-threading-readerwriterlockslim.md | 16 +- .../system-threading-tasks-task.md | 30 ++-- .../system-threading-tasks-taskscheduler.md | 6 +- .../system-threading-thread.md | 14 +- .../system-timespan-parse.md | 4 +- .../system-timespan-tryparse.md | 4 +- .../runtime-libraries/system-timespan.md | 8 +- .../system-type-getproperty.md | 6 +- .../runtime-libraries/system-type-gettype.md | 22 +-- .../system-type-makegenerictype.md | 14 +- .../runtime-libraries/system-type.md | 26 ++-- .../system-typeinitializationexception.md | 4 +- .../runtime-libraries/system-uri.md | 8 +- .../runtime-libraries/system-version.md | 8 +- .../system-xml-linq-xname.md | 4 +- .../system-xml-linq-xnamespace.md | 4 +- .../system-xml-serialization-xmlserializer.md | 8 +- .../system-xml-xmlconvert.md | 18 +-- .../system-xml-xmldocument.md | 12 +- .../system-xml-xmlreader-create.md | 54 +++---- .../runtime-libraries/system-xml-xmlreader.md | 120 +++++++-------- ...tem-xml-xmlreadersettings-dtdprocessing.md | 6 +- .../system-xml-xmlreadersettings-schemas.md | 4 +- .../system-xml-xmlreadersettings.md | 6 +- .../system-xml-xmlresolver.md | 6 +- .../system-xml-xmlsecureresolver.md | 16 +- .../system-xml-xmltextreader.md | 8 +- .../system-xml-xmltextwriter.md | 6 +- .../runtime-libraries/system-xml-xmlwriter.md | 52 +++---- .../system-xml-xsl-xslcompiledtransform.md | 10 +- 148 files changed, 1368 insertions(+), 1367 deletions(-) diff --git a/docs/fundamentals/runtime-libraries/includes/context.md b/docs/fundamentals/runtime-libraries/includes/context.md index 89814007b303e..48e7573b5ca2e 100644 --- a/docs/fundamentals/runtime-libraries/includes/context.md +++ b/docs/fundamentals/runtime-libraries/includes/context.md @@ -1 +1,2 @@ -This article provides supplementary remarks to the reference documentation for this API. +> [!NOTE] +> This article provides supplementary remarks to the reference documentation for this API. diff --git a/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md b/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md index c2a5655969efc..59b297b5d3fa0 100644 --- a/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md +++ b/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md @@ -1,16 +1,16 @@ -Using character-based indexing with the property can be extremely slow under the following conditions: +Using character-based indexing with the property can be extremely slow under the following conditions: - The instance is large (for example, it consists of several tens of thousands of characters). -- The is "chunky." That is, repeated calls to methods such as have automatically expanded the object's property and allocated new chunks of memory to it. +- The is "chunky." That is, repeated calls to methods such as have automatically expanded the object's property and allocated new chunks of memory to it. Performance is severely impacted because each character access walks the entire linked list of chunks to find the correct buffer to index into. > [!NOTE] -> Even for a large "chunky" object, using the property for index-based access to one or a small number of characters has a negligible performance impact; typically, it is an **O(n)** operation. The significant performance impact occurs when iterating the characters in the object, which is an **O(n^2)** operation. +> Even for a large "chunky" object, using the property for index-based access to one or a small number of characters has a negligible performance impact; typically, it is an **O(n)** operation. The significant performance impact occurs when iterating the characters in the object, which is an **O(n^2)** operation. If you encounter performance issues when using character-based indexing with objects, you can use any of the following workarounds: -- Convert the instance to a by calling the method, then access the characters in the string. +- Convert the instance to a by calling the method, then access the characters in the string. - Copy the contents of the existing object to a new pre-sized object. Performance improves because the new object is not chunky. For example: diff --git a/docs/fundamentals/runtime-libraries/microsoft-win32-registry.md b/docs/fundamentals/runtime-libraries/microsoft-win32-registry.md index 8d88d270e2053..8731a2a88ae6d 100644 --- a/docs/fundamentals/runtime-libraries/microsoft-win32-registry.md +++ b/docs/fundamentals/runtime-libraries/microsoft-win32-registry.md @@ -27,7 +27,7 @@ Hardware devices can place information in the registry automatically using the P ## Static methods for getting and setting values -The class also contains `static` and methods for setting and retrieving values from registry keys. These methods open and close registry keys each time they're used. So when you access a large number of values, they don't perform as well as analogous methods in the class. +The class also contains `static` and methods for setting and retrieving values from registry keys. These methods open and close registry keys each time they're used. So when you access a large number of values, they don't perform as well as analogous methods in the class. The class also provides methods that allow you to: diff --git a/docs/fundamentals/runtime-libraries/system-appcontext.md b/docs/fundamentals/runtime-libraries/system-appcontext.md index 643607ce24129..d76b16b288eef 100644 --- a/docs/fundamentals/runtime-libraries/system-appcontext.md +++ b/docs/fundamentals/runtime-libraries/system-appcontext.md @@ -26,13 +26,13 @@ It's beneficial to use a consistent format for switch names, since they're a for - *Switch*.*namespace*.*switchname* - *Switch*.*library*.*switchname* -Once you define and document the switch, callers can use it by calling the method programmatically. .NET Framework apps can also use the switch by adding an [``](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) element to their application configuration file or by using the registry. For more information about how callers use and set the value of configuration switches, see the [AppContext for library consumers](#appcontext-for-library-consumers) section. +Once you define and document the switch, callers can use it by calling the method programmatically. .NET Framework apps can also use the switch by adding an [``](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) element to their application configuration file or by using the registry. For more information about how callers use and set the value of configuration switches, see the [AppContext for library consumers](#appcontext-for-library-consumers) section. -In .NET Framework, when the common language runtime runs an application, it automatically reads the registry's compatibility settings and loads the application configuration file to populate the application's instance. Because the instance is populated either programmatically by the caller or by the runtime, .NET Framework apps don't have to take any action, such as calling the method, to configure the instance. +In .NET Framework, when the common language runtime runs an application, it automatically reads the registry's compatibility settings and loads the application configuration file to populate the application's instance. Because the instance is populated either programmatically by the caller or by the runtime, .NET Framework apps don't have to take any action, such as calling the method, to configure the instance. ### Check the setting -You can check if a consumer has declared the value of the switch and act appropriately by calling the method. The method returns `true` if the `switchName` argument is found, and its `isEnabled` argument indicates the value of the switch. Otherwise, the method returns `false`. +You can check if a consumer has declared the value of the switch and act appropriately by calling the method. The method returns `true` if the `switchName` argument is found, and its `isEnabled` argument indicates the value of the switch. Otherwise, the method returns `false`. ### Example @@ -86,7 +86,7 @@ When the application is run with the configuration file present, it produces the If you're the consumer of a library, the class allows you to take advantage of a library or library method's opt-out mechanism for new functionality. Individual methods of the class library that you are calling define particular switches that enable or disable a new behavior. The value of the switch is a Boolean. If it is `false`, which is typically the default value, the new behavior is enabled; if it is `true`, the new behavior is disabled, and the member behaves as it did previously. -You can set the value of a switch by calling the method in your code. The `switchName` argument defines the switch name, and the `isEnabled` property defines the value of the switch. Because is a static class, it is available on a per-application domain basis. Calling the has application scope; that is, it affects only the application. +You can set the value of a switch by calling the method in your code. The `switchName` argument defines the switch name, and the `isEnabled` property defines the value of the switch. Because is a static class, it is available on a per-application domain basis. Calling the has application scope; that is, it affects only the application. .NET Framework apps have additional ways to set the value of a switch: diff --git a/docs/fundamentals/runtime-libraries/system-appdomain-unhandledexception.md b/docs/fundamentals/runtime-libraries/system-appdomain-unhandledexception.md index 2b312ba82ea3e..a5f4fdde13ec1 100644 --- a/docs/fundamentals/runtime-libraries/system-appdomain-unhandledexception.md +++ b/docs/fundamentals/runtime-libraries/system-appdomain-unhandledexception.md @@ -30,6 +30,6 @@ For more information about handling events, see [Handling and Raising Events](.. For certain application models, the event can be preempted by other events if the unhandled exception occurs in the main application thread. -In applications that use Windows Forms, unhandled exceptions in the main application thread cause the event to be raised. If this event is handled, the default behavior is that the unhandled exception does not terminate the application, although the application is left in an unknown state. In that case, the event is not raised. This behavior can be changed by using the application configuration file, or by using the method to change the mode to before the event handler is hooked up. This applies only to the main application thread. The event is raised for unhandled exceptions thrown in other threads. +In applications that use Windows Forms, unhandled exceptions in the main application thread cause the event to be raised. If this event is handled, the default behavior is that the unhandled exception does not terminate the application, although the application is left in an unknown state. In that case, the event is not raised. This behavior can be changed by using the application configuration file, or by using the method to change the mode to before the event handler is hooked up. This applies only to the main application thread. The event is raised for unhandled exceptions thrown in other threads. The Visual Basic application framework provides another event for unhandled exceptions in the main application thread—the event. This event has an event arguments object with the same name as the event arguments object used by , but with different properties. In particular, this event arguments object has an property that allows the application to continue running, ignoring the unhandled exception (and leaving the application in an unknown state). In that case, the event is not raised. diff --git a/docs/fundamentals/runtime-libraries/system-boolean.md b/docs/fundamentals/runtime-libraries/system-boolean.md index d7e4e485526cf..e60ff362f75ee 100644 --- a/docs/fundamentals/runtime-libraries/system-boolean.md +++ b/docs/fundamentals/runtime-libraries/system-boolean.md @@ -15,9 +15,9 @@ A instance can have either of two values: `true` or `false The structure provides methods that support the following tasks: -- Converting Boolean values to strings: -- Parsing strings to convert them to Boolean values: and -- Comparing values: and +- Converting Boolean values to strings: +- Parsing strings to convert them to Boolean values: and +- Comparing values: and This article explains these tasks and other usage details. @@ -25,9 +25,9 @@ This article explains these tasks and other usage details. The string representation of a is either "True" for a `true` value or "False" for a `false` value. The string representation of a value is defined by the read-only and fields. -You use the method to convert Boolean values to strings. The Boolean structure includes two overloads: the parameterless method and the method, which includes a parameter that controls formatting. However, because this parameter is ignored, the two overloads produce identical strings. The method does not support culture-sensitive formatting. +You use the method to convert Boolean values to strings. The Boolean structure includes two overloads: the parameterless method and the method, which includes a parameter that controls formatting. However, because this parameter is ignored, the two overloads produce identical strings. The method does not support culture-sensitive formatting. -The following example illustrates formatting with the method. Note that the C# and VB examples use the [composite formatting](../../standard/base-types/composite-formatting.md) feature, while the F# example uses [string interpolation](../../fsharp/language-reference/interpolated-strings.md). In both cases the method is called implicitly. +The following example illustrates formatting with the method. Note that the C# and VB examples use the [composite formatting](../../standard/base-types/composite-formatting.md) feature, while the F# example uses [string interpolation](../../fsharp/language-reference/interpolated-strings.md). In both cases the method is called implicitly. :::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/tostring1.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/tostring1.fs" id="Snippet3"::: @@ -39,7 +39,7 @@ Because the structure can have only two values, it is easy :::code language="vb" source="./snippets/System/Boolean/Overview/vb/tostring2.vb" id="Snippet4"::: :::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/tostring2.fs" id="Snippet4"::: -For more complex custom formatting operations, including culture-sensitive formatting, you can call the method and provide an implementation. The following example implements the and interfaces to provide culture-sensitive Boolean strings for the English (United States), French (France), and Russian (Russia) cultures. +For more complex custom formatting operations, including culture-sensitive formatting, you can call the method and provide an implementation. The following example implements the and interfaces to provide culture-sensitive Boolean strings for the English (United States), French (France), and Russian (Russia) cultures. :::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/format3.cs" id="Snippet5"::: :::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/format3.fs" id="Snippet5"::: @@ -51,11 +51,11 @@ Optionally, you can use [resource files](/dotnet/framework/resources/) to define The structure implements the interface. As a result, you can use the class to perform conversions between a value and any other primitive type in .NET, or you can call the structure's explicit implementations. However, conversions between a and the following types are not supported, so the corresponding conversion methods throw an exception: -- Conversion between and (the and methods). +- Conversion between and (the and methods). -- Conversion between and (the and methods). +- Conversion between and (the and methods). -All conversions from integral or floating-point numbers to Boolean values convert non-zero values to `true` and zero values to `false`. The following example illustrates this by calling selected overloads of the class. +All conversions from integral or floating-point numbers to Boolean values convert non-zero values to `true` and zero values to `false`. The following example illustrates this by calling selected overloads of the class. :::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/conversion1.cs" id="Snippet6"::: :::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/conversion1.fs" id="Snippet6"::: @@ -71,9 +71,9 @@ For conversions from to string values, see the [Format Boo ## Parse Boolean values -The structure includes two static parsing methods, and , that convert a string to a Boolean value. The string representation of a Boolean value is defined by the case-insensitive equivalents of the values of the and fields, which are "True" and "False", respectively. In other words, the only strings that parse successfully are "True", "False", "true", "false", or some mixed-case equivalent. You cannot successfully parse numeric strings such as "0" or "1". Leading or trailing white-space characters are not considered when performing the string comparison. +The structure includes two static parsing methods, and , that convert a string to a Boolean value. The string representation of a Boolean value is defined by the case-insensitive equivalents of the values of the and fields, which are "True" and "False", respectively. In other words, the only strings that parse successfully are "True", "False", "true", "false", or some mixed-case equivalent. You cannot successfully parse numeric strings such as "0" or "1". Leading or trailing white-space characters are not considered when performing the string comparison. -The following example uses the and methods to parse a number of strings. Note that only the case-insensitive equivalents of "True" and "False" can be successfully parsed. +The following example uses the and methods to parse a number of strings. Note that only the case-insensitive equivalents of "True" and "False" can be successfully parsed. :::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/parse2.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/parse2.fs" id="Snippet2"::: @@ -87,7 +87,7 @@ If you're programming in Visual Basic, you can use the `CBool` function to conve ## Compare Boolean values -Because Boolean values are either `true` or `false`, there is little reason to explicitly call the method, which indicates whether an instance is greater than, less than, or equal to a specified value. Typically, to compare two Boolean variables, you call the method or use your language's equality operator. +Because Boolean values are either `true` or `false`, there is little reason to explicitly call the method, which indicates whether an instance is greater than, less than, or equal to a specified value. Typically, to compare two Boolean variables, you call the method or use your language's equality operator. However, when you want to compare a Boolean variable with the literal Boolean value `true` or `false`, it's not necessary to do an explicit comparison, because the result of evaluating a Boolean value is that Boolean value. For example, the following two expressions are equivalent, but the second is more compact. However, both techniques offer comparable performance. @@ -111,9 +111,9 @@ The byte's low-order bit is used to represent its value. A value of 1 represents > [!TIP] > You can use the structure to work with sets of Boolean values. -You can convert a Boolean value to its binary representation by calling the method. The method returns a byte array with a single element. To restore a Boolean value from its binary representation, you can call the method. +You can convert a Boolean value to its binary representation by calling the method. The method returns a byte array with a single element. To restore a Boolean value from its binary representation, you can call the method. -The following example calls the method to convert a Boolean value to its binary representation and displays the individual bits of the value, and then calls the method to restore the value from its binary representation. +The following example calls the method to convert a Boolean value to its binary representation and displays the individual bits of the value, and then calls the method to restore the value from its binary representation. :::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/binary1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/binary1.fs" id="Snippet1"::: @@ -125,7 +125,7 @@ This section illustrates how Boolean values are used in apps. The first section ### Boolean values as flags -Boolean variables are most commonly used as flags, to signal the presence or absence of some condition. For example, in the method, the final parameter, `ignoreCase`, is a flag that indicates whether the comparison of two strings is case-insensitive (`ignoreCase` is `true`) or case-sensitive (`ignoreCase` is `false`). The value of the flag can then be evaluated in a conditional statement. +Boolean variables are most commonly used as flags, to signal the presence or absence of some condition. For example, in the method, the final parameter, `ignoreCase`, is a flag that indicates whether the comparison of two strings is case-insensitive (`ignoreCase` is `true`) or case-sensitive (`ignoreCase` is `false`). The value of the flag can then be evaluated in a conditional statement. The following example uses a simple console app to illustrate the use of Boolean variables as flags. The app accepts command-line parameters that enable output to be redirected to a specified file (the `/f` switch), and that enable output to be sent both to a specified file and to the console (the `/b` switch). The app defines a flag named `isRedirected` to indicate whether output is to be sent to a file, and a flag named `isBoth` to indicate that output should be sent to the console. The F# example uses a [recursive function](../../fsharp/language-reference/functions/recursive-functions-the-rec-keyword.md) to parse the arguments. diff --git a/docs/fundamentals/runtime-libraries/system-byte.md b/docs/fundamentals/runtime-libraries/system-byte.md index 5cd97c14c7ae2..55d28327a0fed 100644 --- a/docs/fundamentals/runtime-libraries/system-byte.md +++ b/docs/fundamentals/runtime-libraries/system-byte.md @@ -35,7 +35,7 @@ You can instantiate a value in several ways: :::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/tobyte1.fs" id="Snippet4"::: :::code language="vb" source="./snippets/System/Convert/Overview/vb/tobyte1.vb" id="Snippet4"::: -- You can call the or method to convert the string representation of a value to a . The string can contain either decimal or hexadecimal digits. The following example illustrates the parse operation by using both a decimal and a hexadecimal string. +- You can call the or method to convert the string representation of a value to a . The string can contain either decimal or hexadecimal digits. The following example illustrates the parse operation by using both a decimal and a hexadecimal string. :::code language="csharp" source="./snippets/System/Byte/Overview/csharp/byteinstantiation1.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/byteinstantiation1.fs" id="Snippet3"::: @@ -45,7 +45,7 @@ You can instantiate a value in several ways: The type supports standard mathematical operations such as addition, subtraction, division, multiplication, subtraction, negation, and unary negation. Like the other integral types, the type also supports the bitwise `AND`, `OR`, `XOR`, left shift, and right shift operators. -You can use the standard numeric operators to compare two values, or you can call the or method. +You can use the standard numeric operators to compare two values, or you can call the or method. You can also call the members of the class to perform a wide range of numeric operations, including getting the absolute value of a number, calculating the quotient and remainder from integral division, determining the maximum or minimum value of two integers, getting the sign of a number, and rounding a number. @@ -59,7 +59,7 @@ To format a value as an integral string with no leading zeros :::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/formatting1.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/Byte/Overview/vb/formatting1.vb" id="Snippet1"::: -You can also format a value as a binary, octal, decimal, or hexadecimal string by calling the method and supplying the base as the method's second parameter. The following example calls this method to display the binary, octal, and hexadecimal representations of an array of byte values. +You can also format a value as a binary, octal, decimal, or hexadecimal string by calling the method and supplying the base as the method's second parameter. The following example calls this method to display the binary, octal, and hexadecimal representations of an array of byte values. :::code language="csharp" source="./snippets/System/Byte/Overview/csharp/formatting1.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/formatting1.fs" id="Snippet2"::: @@ -67,7 +67,7 @@ You can also format a value as a binary, octal, decimal, or h ## Work with non-decimal Byte values -In addition to working with individual bytes as decimal values, you might want to perform bitwise operations with byte values, or work with byte arrays or with the binary or hexadecimal representations of byte values. For example, overloads of the method can convert each of the primitive data types to a byte array, and the method converts a value to a byte array. +In addition to working with individual bytes as decimal values, you might want to perform bitwise operations with byte values, or work with byte arrays or with the binary or hexadecimal representations of byte values. For example, overloads of the method can convert each of the primitive data types to a byte array, and the method converts a value to a byte array. values are represented in 8 bits by their magnitude only, without a sign bit. This is important to keep in mind when you perform bitwise operations on values or when you work with individual bits. To perform a numeric, Boolean, or comparison operation on any two non-decimal values, both values must use the same representation. diff --git a/docs/fundamentals/runtime-libraries/system-char.md b/docs/fundamentals/runtime-libraries/system-char.md index 687062ee5bef0..7db917accb75e 100644 --- a/docs/fundamentals/runtime-libraries/system-char.md +++ b/docs/fundamentals/runtime-libraries/system-char.md @@ -39,13 +39,13 @@ Multiple 16-bit code units are used to represent single Unicode characters in th Each Unicode character or valid surrogate pair belongs to a Unicode category. In .NET, Unicode categories are represented by members of the enumeration and include values such as , , and , for example. -To determine the Unicode category of a character, call the method. For example, the following example calls the to display the Unicode category of each character in a string. The example works correctly only if there are no surrogate pairs in the instance. +To determine the Unicode category of a character, call the method. For example, the following example calls the to display the Unicode category of each character in a string. The example works correctly only if there are no surrogate pairs in the instance. :::code language="csharp" source="./snippets/System/Char/Overview/csharp/GetUnicodeCategory3.cs" id="Snippet6"::: :::code language="fsharp" source="./snippets/System/Char/Overview/fsharp/GetUnicodeCategory3.fs" id="Snippet6"::: :::code language="vb" source="./snippets/System/Char/Overview/vb/GetUnicodeCategory3.vb" id="Snippet6"::: -Internally, for characters outside the ASCII range (U+0000 through U+00FF), the method depends on Unicode categories reported by the class. Starting with .NET Framework 4.6.2, Unicode characters are classified based on [The Unicode Standard, Version 8.0.0](https://www.unicode.org/versions/Unicode8.0.0/). In versions of .NET Framework from .NET Framework 4 to .NET Framework 4.6.1, they are classified based on [The Unicode Standard, Version 6.3.0](https://www.unicode.org/versions/Unicode6.3.0/). +Internally, for characters outside the ASCII range (U+0000 through U+00FF), the method depends on Unicode categories reported by the class. Starting with .NET Framework 4.6.2, Unicode characters are classified based on [The Unicode Standard, Version 8.0.0](https://www.unicode.org/versions/Unicode8.0.0/). In versions of .NET Framework from .NET Framework 4 to .NET Framework 4.6.1, they are classified based on [The Unicode Standard, Version 6.3.0](https://www.unicode.org/versions/Unicode6.3.0/). ## Characters and text elements @@ -59,7 +59,7 @@ You can do the following to avoid the assumption that a objec - You can work with a object in its entirety instead of working with its individual characters to represent and analyze linguistic content. -- You can use as shown in the following example: +- You can use as shown in the following example: :::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/CountLettersInString.cs" id="SnippetGoodExample"::: :::code language="fsharp" source="./snippets/System.Text/Rune/Overview/fsharp/CountLettersInString.fs" id="SnippetGoodExample"::: @@ -70,7 +70,7 @@ You can do the following to avoid the assumption that a objec :::code language="fsharp" source="./snippets/System/Char/Overview/fsharp/textelements2a.fs" id="Snippet4"::: :::code language="vb" source="./snippets/System/Char/Overview/vb/textelements2a.vb" id="Snippet4"::: -- If a string contains a base character that has one or more combining characters, you can call the method to convert the substring to a single UTF-16 encoded code unit. The following example calls the method to convert the base character U+0061 (LATIN SMALL LETTER A) and combining character U+0308 (COMBINING DIAERESIS) to U+00E4 (LATIN SMALL LETTER A WITH DIAERESIS). +- If a string contains a base character that has one or more combining characters, you can call the method to convert the substring to a single UTF-16 encoded code unit. The following example calls the method to convert the base character U+0061 (LATIN SMALL LETTER A) and combining character U+0308 (COMBINING DIAERESIS) to U+00E4 (LATIN SMALL LETTER A WITH DIAERESIS). :::code language="csharp" source="./snippets/System/Char/Overview/csharp/normalized.cs" id="Snippet5"::: :::code language="fsharp" source="./snippets/System/Char/Overview/fsharp/normalized.fs" id="Snippet5"::: @@ -82,15 +82,15 @@ The structure provides methods to compare |To do this|Use these `System.Char` methods| |----------------|-------------------------------------| -|Compare objects| and | -|Convert a code point to a string|

See also the type.| -|Convert a object or a surrogate pair of objects to a code point|For a single character:

For a surrogate pair or a character in a string:

See also the type.| -|Get the Unicode category of a character|

See also .| -|Determine whether a character is in a particular Unicode category such as digit, letter, punctuation, control character, and so on|, , , , , , , , , , , , , , and

See also corresponding methods on the type.| -|Convert a object that represents a number to a numeric value type|

See also .| -|Convert a character in a string into a object| and | -|Convert a object to a object|| -|Change the case of a object|, , , and

See also corresponding methods on the type.| +|Compare objects| and | +|Convert a code point to a string|

See also the type.| +|Convert a object or a surrogate pair of objects to a code point|For a single character:

For a surrogate pair or a character in a string:

See also the type.| +|Get the Unicode category of a character|

See also .| +|Determine whether a character is in a particular Unicode category such as digit, letter, punctuation, control character, and so on|, , , , , , , , , , , , , , and

See also corresponding methods on the type.| +|Convert a object that represents a number to a numeric value type|

See also .| +|Convert a character in a string into a object| and | +|Convert a object to a object|| +|Change the case of a object|, , , and

See also corresponding methods on the type.| ## Char values and interop diff --git a/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md b/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md index 2959874215da6..cc8c9a4618871 100644 --- a/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md +++ b/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md @@ -10,49 +10,49 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order. +The class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order. -The capacity of a object is the number of elements that the object can hold. A object's capacity automatically increases as elements are added to the object. +The capacity of a object is the number of elements that the object can hold. A object's capacity automatically increases as elements are added to the object. -The class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the or collections. In simple terms, the class can be thought of as a collection without values. +The class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the or collections. In simple terms, the class can be thought of as a collection without values. -A collection is not sorted and cannot contain duplicate elements. If order or element duplication is more important than performance for your application, consider using the class together with the method. +A collection is not sorted and cannot contain duplicate elements. If order or element duplication is more important than performance for your application, consider using the class together with the method. - provides many mathematical set operations, such as set addition (unions) and set subtraction. The following table lists the provided operations and their mathematical equivalents. + provides many mathematical set operations, such as set addition (unions) and set subtraction. The following table lists the provided operations and their mathematical equivalents. |HashSet operation|Mathematical equivalent| |-------------------------------|-----------------------------| -||Union or set addition| -||Intersection| -||Set subtraction| -||Symmetric difference| +||Union or set addition| +||Intersection| +||Set subtraction| +||Symmetric difference| -In addition to the listed set operations, the class also provides methods for determining set equality, overlap of sets, and whether a set is a subset or superset of another set. +In addition to the listed set operations, the class also provides methods for determining set equality, overlap of sets, and whether a set is a subset or superset of another set. -**.NET Framework only:** For very large objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the `enabled` attribute of the [``](../../framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md) configuration element to `true` in the runtime environment. +**.NET Framework only:** For very large objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the `enabled` attribute of the [``](../../framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md) configuration element to `true` in the runtime environment. -The class implements the interface. +The class implements the interface. ## HashSet and LINQ set operations -LINQ provides access to the `Distinct`, `Union`, `Intersect`, and `Except` set operations on any data source that implements the or interfaces. provides a larger and more robust collection of set operations. For example, provides comparisons such as and . +LINQ provides access to the `Distinct`, `Union`, `Intersect`, and `Except` set operations on any data source that implements the or interfaces. provides a larger and more robust collection of set operations. For example, provides comparisons such as and . -The primary difference between LINQ set operations and operations is that LINQ set operations always return a new collection, whereas the equivalent methods modify the current collection. +The primary difference between LINQ set operations and operations is that LINQ set operations always return a new collection, whereas the equivalent methods modify the current collection. -Typically, if you must create a new set or if your application needs access only to the provided set operations, using LINQ set operations on any collection or array will be sufficient. However, if your application requires access to additional set operations, or if it is not desirable or necessary to create a new collection, use the class. +Typically, if you must create a new set or if your application needs access only to the provided set operations, using LINQ set operations on any collection or array will be sufficient. However, if your application requires access to additional set operations, or if it is not desirable or necessary to create a new collection, use the class. -The following table shows the operations and their equivalent LINQ set operations. +The following table shows the operations and their equivalent LINQ set operations. |HashSet operation|LINQ equivalent| |-------------------------------|---------------------| -||| -||| -||| -|Not provided.|| -||Not provided.| -||Not provided.| -||Not provided.| -||Not provided.| -||Not provided.| -||Not provided.| -||Not provided.| +||| +||| +||| +|Not provided.|| +||Not provided.| +||Not provided.| +||Not provided.| +||Not provided.| +||Not provided.| +||Not provided.| +||Not provided.| diff --git a/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md b/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md index 41808b724d333..4fd286340ceee 100644 --- a/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md +++ b/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md @@ -11,59 +11,59 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The class is the generic equivalent of the class. It implements the generic interface by using an array whose size is dynamically increased as required. +The class is the generic equivalent of the class. It implements the generic interface by using an array whose size is dynamically increased as required. -You can add items to a by using the or methods. +You can add items to a by using the or methods. -The class uses both an equality comparer and an ordering comparer. +The class uses both an equality comparer and an ordering comparer. -- Methods such as , , , and use an equality comparer for the list elements. The default equality comparer for type `T` is determined as follows. If type `T` implements the generic interface, then the equality comparer is the method of that interface; otherwise, the default equality comparer is . +- Methods such as , , , and use an equality comparer for the list elements. The default equality comparer for type `T` is determined as follows. If type `T` implements the generic interface, then the equality comparer is the method of that interface; otherwise, the default equality comparer is . -- Methods such as and use an ordering comparer for the list elements. The default comparer for type `T` is determined as follows. If type `T` implements the generic interface, then the default comparer is the method of that interface; otherwise, if type `T` implements the nongeneric interface, then the default comparer is the method of that interface. If type `T` implements neither interface, then there is no default comparer, and a comparer or comparison delegate must be provided explicitly. +- Methods such as and use an ordering comparer for the list elements. The default comparer for type `T` is determined as follows. If type `T` implements the generic interface, then the default comparer is the method of that interface; otherwise, if type `T` implements the nongeneric interface, then the default comparer is the method of that interface. If type `T` implements neither interface, then there is no default comparer, and a comparer or comparison delegate must be provided explicitly. -The is not guaranteed to be sorted. You must sort the before performing operations (such as ) that require the to be sorted. +The is not guaranteed to be sorted. You must sort the before performing operations (such as ) that require the to be sorted. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based. -**.NET Framework only:** For very large objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the `enabled` attribute of the [``](../../framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md) configuration element to `true` in the runtime environment. +**.NET Framework only:** For very large objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the `enabled` attribute of the [``](../../framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md) configuration element to `true` in the runtime environment. - accepts `null` as a valid value for reference types and allows duplicate elements. + accepts `null` as a valid value for reference types and allows duplicate elements. -For an immutable version of the class, see . +For an immutable version of the class, see . ## Performance considerations -In deciding whether to use the or class, both of which have similar functionality, remember that the class performs better in most cases and is type safe. If a reference type is used for type `T` of the class, the behavior of the two classes is identical. However, if a value type is used for type `T`, you need to consider implementation and boxing issues. +In deciding whether to use the or class, both of which have similar functionality, remember that the class performs better in most cases and is type safe. If a reference type is used for type `T` of the class, the behavior of the two classes is identical. However, if a value type is used for type `T`, you need to consider implementation and boxing issues. -If a value type is used for type `T`, the compiler generates an implementation of the class specifically for that value type. That means a list element of a object does not have to be boxed before the element can be used, and after about 500 list elements are created, the memory saved by not boxing list elements is greater than the memory used to generate the class implementation. +If a value type is used for type `T`, the compiler generates an implementation of the class specifically for that value type. That means a list element of a object does not have to be boxed before the element can be used, and after about 500 list elements are created, the memory saved by not boxing list elements is greater than the memory used to generate the class implementation. -Make certain the value type used for type `T` implements the generic interface. If not, methods such as must call the method, which boxes the affected list element. If the value type implements the interface and you own the source code, also implement the generic interface to prevent the and methods from boxing list elements. If you do not own the source code, pass an object to the and methods. +Make certain the value type used for type `T` implements the generic interface. If not, methods such as must call the method, which boxes the affected list element. If the value type implements the interface and you own the source code, also implement the generic interface to prevent the and methods from boxing list elements. If you do not own the source code, pass an object to the and methods. -It's to your advantage to use the type-specific implementation of the class instead of using the class or writing a strongly typed wrapper collection yourself. That's because your implementation must do what .NET does for you already, and the .NET runtime can share common intermediate language code and metadata, which your implementation cannot. +It's to your advantage to use the type-specific implementation of the class instead of using the class or writing a strongly typed wrapper collection yourself. That's because your implementation must do what .NET does for you already, and the .NET runtime can share common intermediate language code and metadata, which your implementation cannot. ## F# considerations -The class is used infrequently in F# code. Instead, [Lists](../../fsharp/language-reference/lists.md), which are immutable, singly-linked lists, are typically preferred. An F# `List` provides an ordered, immutable series of values, and is supported for use in functional-style development. When used from F#, the class is typically referred to by the `ResizeArray<'T>` type abbreviation to avoid naming conflicts with F# Lists. +The class is used infrequently in F# code. Instead, [Lists](../../fsharp/language-reference/lists.md), which are immutable, singly-linked lists, are typically preferred. An F# `List` provides an ordered, immutable series of values, and is supported for use in functional-style development. When used from F#, the class is typically referred to by the `ResizeArray<'T>` type abbreviation to avoid naming conflicts with F# Lists. ## Examples -The following example demonstrates how to add, remove, and insert a simple business object in a . +The following example demonstrates how to add, remove, and insert a simple business object in a . :::code language="csharp" source="./snippets/System.Collections.Generic/ListT/Overview/csharp/program.cs" id="snippet1"::: :::code language="vb" source="./snippets/System.Collections.Generic/List/Overview/vb/module1.vb" id="snippet1"::: :::code language="fsharp" source="./snippets/System.Collections.Generic/ListT/Overview/fsharp/addremoveinsert.fs" id="snippet1"::: -The following example demonstrates several properties and methods of the generic class of type string. (For an example of a of complex types, see the method.) +The following example demonstrates several properties and methods of the generic class of type string. (For an example of a of complex types, see the method.) -The parameterless constructor is used to create a list of strings with the default capacity. The property is displayed and then the method is used to add several items. The items are listed, and the property is displayed again, along with the property, to show that the capacity has been increased as needed. +The parameterless constructor is used to create a list of strings with the default capacity. The property is displayed and then the method is used to add several items. The items are listed, and the property is displayed again, along with the property, to show that the capacity has been increased as needed. -The method is used to test for the presence of an item in the list, the method is used to insert a new item in the middle of the list, and the contents of the list are displayed again. +The method is used to test for the presence of an item in the list, the method is used to insert a new item in the middle of the list, and the contents of the list are displayed again. -The default property (the indexer in C#) is used to retrieve an item, the method is used to remove the first instance of the duplicate item added earlier, and the contents are displayed again. The method always removes the first instance it encounters. +The default property (the indexer in C#) is used to retrieve an item, the method is used to remove the first instance of the duplicate item added earlier, and the contents are displayed again. The method always removes the first instance it encounters. -The method is used to reduce the capacity to match the count, and the and properties are displayed. If the unused capacity had been less than 10 percent of total capacity, the list would not have been resized. +The method is used to reduce the capacity to match the count, and the and properties are displayed. If the unused capacity had been less than 10 percent of total capacity, the list would not have been resized. -Finally, the method is used to remove all items from the list, and the and properties are displayed. +Finally, the method is used to remove all items from the list, and the and properties are displayed. :::code language="csharp" source="./snippets/System.Collections.Generic/ListT/Overview/csharp/source.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System.Collections.Generic/List/Overview/vb/source.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md b/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md index 44d29af53dc6f..60f9675347ea5 100644 --- a/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md +++ b/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md @@ -7,11 +7,11 @@ ms.date: 01/24/2024 [!INCLUDE [context](includes/context.md)] -The method does not modify the key embedded in `item`; it simply replaces the key saved in the lookup dictionary. Therefore, if `newKey` is different from the key that is embedded in `item`, you cannot access `item` by using the key returned by . +The method does not modify the key embedded in `item`; it simply replaces the key saved in the lookup dictionary. Therefore, if `newKey` is different from the key that is embedded in `item`, you cannot access `item` by using the key returned by . -This method does nothing if the does not have a lookup dictionary. +This method does nothing if the does not have a lookup dictionary. -Every key in a must be unique. A key cannot be `null`. +Every key in a must be unique. A key cannot be `null`. This method is an O(1) operation. @@ -19,4 +19,4 @@ This method is an O(1) operation. Before modifying the key embedded in an item, you must call this method to update the key in the lookup dictionary. If the dictionary creation threshold is -1, calling this method is not necessary. -Do not expose the method as a public method of a derived class. Misuse of this method puts the lookup dictionary out of sync with item keys. For example, setting the key to `null` and then setting it to another value adds multiple keys for an item to the lookup dictionary. Expose this method internally to allow mutable item keys: When the key for an item changes, this method is used to change the key in the lookup dictionary. +Do not expose the method as a public method of a derived class. Misuse of this method puts the lookup dictionary out of sync with item keys. For example, setting the key to `null` and then setting it to another value adds multiple keys for an item to the lookup dictionary. Expose this method internally to allow mutable item keys: When the key for an item changes, this method is used to change the key in the lookup dictionary. diff --git a/docs/fundamentals/runtime-libraries/system-collections-objectmodel-observablecollection{t}.md b/docs/fundamentals/runtime-libraries/system-collections-objectmodel-observablecollection{t}.md index 22d357e956ce7..cb036148c2182 100644 --- a/docs/fundamentals/runtime-libraries/system-collections-objectmodel-observablecollection{t}.md +++ b/docs/fundamentals/runtime-libraries/system-collections-objectmodel-observablecollection{t}.md @@ -7,15 +7,15 @@ ms.date: 01/02/2024 [!INCLUDE [context](includes/context.md)] -The class represents a dynamic data collection that provides notifications when items get added or removed, or when the whole list is refreshed. +The class represents a dynamic data collection that provides notifications when items get added or removed, or when the whole list is refreshed. In many cases, the data that you work with is a collection of objects. For example, a common scenario in data binding is to use an such as a , , or to display a collection of records. You can enumerate over any collection that implements the interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the UI automatically, the collection must implement the interface. This interface exposes the event, an event that should be raised whenever the underlying collection changes. -The class is a data collection type that implements the interface. +The class is a data collection type that implements the interface. -Before implementing your own collection, consider using or one of the existing collection classes, such as , , and , among many others. If you have an advanced scenario and want to implement your own collection, consider using , which provides a non-generic collection of objects that can be individually accessed by index. Implementing provides the best performance with the data binding engine. +Before implementing your own collection, consider using or one of the existing collection classes, such as , , and , among many others. If you have an advanced scenario and want to implement your own collection, consider using , which provides a non-generic collection of objects that can be individually accessed by index. Implementing provides the best performance with the data binding engine. > [!NOTE] > To fully support transferring data values from binding source objects to binding targets, each object in your collection that supports bindable properties must implement an appropriate property changed notification mechanism such as the interface. @@ -24,12 +24,12 @@ For more information, see "Binding to Collections" in [Data Binding Overview](/d ## Notes on XAML usage - can be used as a XAML object element in Windows Presentation Foundation (WPF), in versions 3.0 and 3.5. However, the usage has substantial limitations. + can be used as a XAML object element in Windows Presentation Foundation (WPF), in versions 3.0 and 3.5. However, the usage has substantial limitations. -- must be the root element, because the `x:TypeArguments` attribute that must be used to specify the constrained type of the generic is only supported on the object element for the root element. +- must be the root element, because the `x:TypeArguments` attribute that must be used to specify the constrained type of the generic is only supported on the object element for the root element. - You must declare an `x:Class` attribute (which entails that the build action for this XAML file must be `Page` or some other build action that compiles the XAML). -- is in a namespace and assembly that are not initially mapped to the default XML namespace. You must map a prefix for the namespace and assembly, and then use that prefix on the object element tag for . +- is in a namespace and assembly that are not initially mapped to the default XML namespace. You must map a prefix for the namespace and assembly, and then use that prefix on the object element tag for . -A more straightforward way to use capabilities from XAML in an application is to declare your own non-generic custom collection class that derives from , and constrains it to a specific type. Then map the assembly that contains this class, and reference it as an object element in your XAML. +A more straightforward way to use capabilities from XAML in an application is to declare your own non-generic custom collection class that derives from , and constrains it to a specific type. Then map the assembly that contains this class, and reference it as an object element in your XAML. diff --git a/docs/fundamentals/runtime-libraries/system-console.md b/docs/fundamentals/runtime-libraries/system-console.md index 998eea3ff44c1..ef3da157114e9 100644 --- a/docs/fundamentals/runtime-libraries/system-console.md +++ b/docs/fundamentals/runtime-libraries/system-console.md @@ -15,22 +15,22 @@ The console is an operating system window where users interact with the operatin ## Console I/O streams -When a console application starts, the operating system automatically associates three I/O streams with the console: standard input stream, standard output stream, and standard error output stream. Your application can read user input from the standard input stream; write normal data to the standard output stream; and write error data to the standard error output stream. These streams are presented to your application as the values of the , , and properties. +When a console application starts, the operating system automatically associates three I/O streams with the console: standard input stream, standard output stream, and standard error output stream. Your application can read user input from the standard input stream; write normal data to the standard output stream; and write error data to the standard error output stream. These streams are presented to your application as the values of the , , and properties. -By default, the value of the property is a object that represents the keyboard, and the values of the and properties are objects that represent a console window. However, you can set these properties to streams that do not represent the console window or keyboard; for example, you can set these properties to streams that represent files. To redirect the standard input, standard output, or standard error stream, call the , , or method, respectively. I/O operations that use these streams are synchronized, which means that multiple threads can read from, or write to, the streams. This means that methods that are ordinarily asynchronous, such as , execute synchronously if the object represents a console stream. +By default, the value of the property is a object that represents the keyboard, and the values of the and properties are objects that represent a console window. However, you can set these properties to streams that do not represent the console window or keyboard; for example, you can set these properties to streams that represent files. To redirect the standard input, standard output, or standard error stream, call the , , or method, respectively. I/O operations that use these streams are synchronized, which means that multiple threads can read from, or write to, the streams. This means that methods that are ordinarily asynchronous, such as , execute synchronously if the object represents a console stream. > [!NOTE] -> Do not use the class to display output in unattended applications, such as server applications. Calls to methods such as and have no effect in GUI applications. +> Do not use the class to display output in unattended applications, such as server applications. Calls to methods such as and have no effect in GUI applications. - class members that work normally when the underlying stream is directed to a console might throw an exception if the stream is redirected, for example, to a file. Program your application to catch exceptions if you redirect a standard stream. You can also use the , , and properties to determine whether a standard stream is redirected before performing an operation that throws an exception. + class members that work normally when the underlying stream is directed to a console might throw an exception if the stream is redirected, for example, to a file. Program your application to catch exceptions if you redirect a standard stream. You can also use the , , and properties to determine whether a standard stream is redirected before performing an operation that throws an exception. -It is sometimes useful to explicitly call the members of the stream objects represented by the , , and properties. For example, by default, the method reads input from the standard input stream. Similarly, the method writes data to the standard output stream, and the data is followed by the default line termination string, which can be found at . However, the class does not provide a corresponding method to write data to the standard error output stream, or a property to change the line termination string for data written to that stream. +It is sometimes useful to explicitly call the members of the stream objects represented by the , , and properties. For example, by default, the method reads input from the standard input stream. Similarly, the method writes data to the standard output stream, and the data is followed by the default line termination string, which can be found at . However, the class does not provide a corresponding method to write data to the standard error output stream, or a property to change the line termination string for data written to that stream. -You can solve this problem by setting the property of the or property to another line termination string. For example, the following C# statement sets the line termination string for the standard error output stream to two carriage return and line feed sequences: +You can solve this problem by setting the property of the or property to another line termination string. For example, the following C# statement sets the line termination string for the standard error output stream to two carriage return and line feed sequences: `Console.Error.NewLine = "\r\n\r\n";` -You can then explicitly call the method of the error output stream object, as in the following C# statement: +You can then explicitly call the method of the error output stream object, as in the following C# statement: `Console.Error.WriteLine();` @@ -52,7 +52,7 @@ In general, the console reads input and writes output by using the current conso :::code language="vb" source="./snippets/System/Console/Overview/vb/unicode1.vb" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Console/Overview/fsharp/unicode1.fs" id="Snippet1"::: -In addition to supporting code pages, the class supports UTF-8 encoding with the class. Beginning with .NET Framework 4.5, the class also supports UTF-16 encoding with the class. To display Unicode characters to the console. you set the property to either or . +In addition to supporting code pages, the class supports UTF-8 encoding with the class. Beginning with .NET Framework 4.5, the class also supports UTF-16 encoding with the class. To display Unicode characters to the console. you set the property to either or . Support for Unicode characters requires the encoder to recognize a particular Unicode character, and also requires a font that has the glyphs needed to render that character. To successfully display Unicode characters to the console, the console font must be set to a non-raster or TrueType font such as Consolas or Lucida Console. The following example shows how you can programmatically change the font from a raster font to Lucida Console. @@ -78,7 +78,7 @@ Unicode support for the console has the following limitations: - Display of characters in complex scripts is not supported. -- Combining character sequences (that is, characters that consist of a base character and one or more combining characters) are displayed as separate characters. To work around this limitation, you can normalize the string to be displayed by calling the method before sending output to the console. In the following example, a string that contains the combining character sequence U+0061 U+0308 is displayed to the console as two characters before the output string is normalized, and as a single character after the method is called. +- Combining character sequences (that is, characters that consist of a base character and one or more combining characters) are displayed as separate characters. To work around this limitation, you can normalize the string to be displayed by calling the method before sending output to the console. In the following example, a string that contains the combining character sequence U+0061 U+0308 is displayed to the console as two characters before the output string is normalized, and as a single character after the method is called. :::code language="csharp" source="./snippets/System/Console/Overview/csharp/normalize1.cs" id="Snippet5"::: :::code language="vb" source="./snippets/System/Console/Overview/vb/normalize1.vb" id="Snippet5"::: @@ -98,47 +98,47 @@ The following example displays a range of Unicode characters to the console. The The class contains the following methods for reading console input and writing console output: -- The overloads of the method read an individual character. +- The overloads of the method read an individual character. -- The method reads an entire line of input. +- The method reads an entire line of input. -- The method overloads convert an instance of a value type, an array of characters, or a set of objects to a formatted or unformatted string, and then write that string to the console. +- The method overloads convert an instance of a value type, an array of characters, or a set of objects to a formatted or unformatted string, and then write that string to the console. -- A parallel set of method overloads output the same string as the overloads but also add a line termination string. +- A parallel set of method overloads output the same string as the overloads but also add a line termination string. The class also contains methods and properties to perform the following operations: -- Get or set the size of the screen buffer. The and properties let you get or set the buffer height and width, respectively, and the method lets you set the buffer size in a single method call. +- Get or set the size of the screen buffer. The and properties let you get or set the buffer height and width, respectively, and the method lets you set the buffer size in a single method call. -- Get or set the size of the console window. The and properties let you get or set the window height and width, respectively, and the method lets you set the window size in a single method call. +- Get or set the size of the console window. The and properties let you get or set the window height and width, respectively, and the method lets you set the window size in a single method call. -- Get or set the size of the cursor. The property specifies the height of the cursor in a character cell. +- Get or set the size of the cursor. The property specifies the height of the cursor in a character cell. -- Get or set the position of the console window relative to the screen buffer. The and properties let you get or set the top row and leftmost column of the screen buffer that appears in the console window, and the method lets you set these values in a single method call. +- Get or set the position of the console window relative to the screen buffer. The and properties let you get or set the top row and leftmost column of the screen buffer that appears in the console window, and the method lets you set these values in a single method call. -- Get or set the position of the cursor by getting or setting the and properties, or set the position of the cursor by calling the method. +- Get or set the position of the cursor by getting or setting the and properties, or set the position of the cursor by calling the method. -- Move or clear data in the screen buffer by calling the or method. +- Move or clear data in the screen buffer by calling the or method. -- Get or set the foreground and background colors by using the and properties, or reset the background and foreground to their default colors by calling the method. +- Get or set the foreground and background colors by using the and properties, or reset the background and foreground to their default colors by calling the method. -- Play the sound of a beep through the console speaker by calling the method. +- Play the sound of a beep through the console speaker by calling the method. ## .NET Core notes -In .NET Framework on the desktop, the class uses the encoding returned by `GetConsoleCP` and `GetConsoleOutputCP`, which typically is a code page encoding. For example code, on systems whose culture is English (United States), code page 437 is the encoding that is used by default. However, .NET Core may make only a limited subset of these encodings available. Where this is the case, is used as the default encoding for the console. +In .NET Framework on the desktop, the class uses the encoding returned by `GetConsoleCP` and `GetConsoleOutputCP`, which typically is a code page encoding. For example code, on systems whose culture is English (United States), code page 437 is the encoding that is used by default. However, .NET Core may make only a limited subset of these encodings available. Where this is the case, is used as the default encoding for the console. If your app depends on specific code page encodings, you can still make them available by doing the following *before* you call any methods: -1. Retrieve the object from the property. +1. Retrieve the object from the property. -2. Pass the object to the method to make the additional encodings supported by the encoding provider available. +2. Pass the object to the method to make the additional encodings supported by the encoding provider available. The class will then automatically use the default system encoding rather than UTF8, provided that you have registered the encoding provider before calling any output methods. ## Examples -The following example demonstrates how to read data from, and write data to, the standard input and output streams. Note that these streams can be redirected by using the and methods. +The following example demonstrates how to read data from, and write data to, the standard input and output streams. Note that these streams can be redirected by using the and methods. :::code language="csharp" source="./snippets/System/Console/Overview/csharp/source.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System/Console/Overview/vb/source.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-convert.md b/docs/fundamentals/runtime-libraries/system-convert.md index e5b78621655d2..9512b39050943 100644 --- a/docs/fundamentals/runtime-libraries/system-convert.md +++ b/docs/fundamentals/runtime-libraries/system-convert.md @@ -17,7 +17,7 @@ The static class contains methods that are primarily used A conversion method exists to convert every base type to every other base type. However, the actual call to a particular conversion method can produce one of five outcomes, depending on the value of the base type at runtime and the target base type. These five outcomes are: -- No conversion. This occurs when an attempt is made to convert from a type to itself (for example, by calling with an argument of type ). In this case, the method simply returns an instance of the original type. +- No conversion. This occurs when an attempt is made to convert from a type to itself (for example, by calling with an argument of type ). In this case, the method simply returns an instance of the original type. - An . This occurs when a particular conversion is not supported. An is thrown for the following conversions: @@ -45,21 +45,21 @@ For example, when a is converted to a , The class includes static methods that you can call to convert integral values to non-decimal string representations, and to convert strings that represent non-decimal numbers to integral values. Each of these conversion methods includes a `base` argument that lets you specify the number system; binary (base 2), octal (base 8), and hexadecimal (base 16), as well as decimal (base 10). There is a set of methods to convert each of the CLS-compliant primitive integral types to a string, and one to convert a string to each of the primitive integral types: -- and , to convert a byte value to and from a string in a specified base. +- and , to convert a byte value to and from a string in a specified base. -- and , to convert a 16-bit signed integer to and from a string in a specified base. +- and , to convert a 16-bit signed integer to and from a string in a specified base. -- and , to convert a 32-bit signed integer to and from a string in a specified base. +- and , to convert a 32-bit signed integer to and from a string in a specified base. -- and , to convert a 64-bit signed integer to and from a string in a specified base. +- and , to convert a 64-bit signed integer to and from a string in a specified base. -- , to convert the string representation of a byte value in a specified format to a signed byte. +- , to convert the string representation of a byte value in a specified format to a signed byte. -- , to convert the string representation of an integer in a specified format to an unsigned 16-bit integer. +- , to convert the string representation of an integer in a specified format to an unsigned 16-bit integer. -- , to convert the string representation of an integer in a specified format to an unsigned 32-bit integer. +- , to convert the string representation of an integer in a specified format to an unsigned 32-bit integer. -- , to convert the string representation of an integer in a specified format to an unsigned 64-bit integer. +- , to convert the string representation of an integer in a specified format to an unsigned 64-bit integer. The following example converts the value of to a string in all supported numeric formats. It then converts the string value back to a value. @@ -71,14 +71,14 @@ The following example converts the value of method supports conversion of any custom type to any base type. To do this, the custom type must implement the interface, which defines methods for converting the implementing type to each of the base types. Conversions that are not supported by a particular type should throw an . -When the method is passed a custom type as its first parameter, or when the `Convert.To`*Type* method (such as or is called and passed an instance of a custom type as its first parameter, the method, in turn, calls the custom type's implementation to perform the conversion. For more information, see [Type Conversion in .NET](../../standard/base-types/type-conversion.md). +When the method is passed a custom type as its first parameter, or when the `Convert.To`*Type* method (such as or is called and passed an instance of a custom type as its first parameter, the method, in turn, calls the custom type's implementation to perform the conversion. For more information, see [Type Conversion in .NET](../../standard/base-types/type-conversion.md). ## Culture-specific formatting information -All the base type conversion methods and the method include overloads that have a parameter of type . For example, the method has the following two overloads: +All the base type conversion methods and the method include overloads that have a parameter of type . For example, the method has the following two overloads: -- -- +- +- The parameter can supply culture-specific formatting information to assist the conversion process. However, it is ignored by most of the base type conversion methods. It is used only by the following base type conversion methods. If a `null` argument is passed to these methods, the object that represents the current culture is used. @@ -86,7 +86,7 @@ The parameter can supply culture-specific formatti - By methods that convert a value to a date and time. The parameter is used by the overload that has parameters of type and . It is also used by the overload that has parameters of type and if the object's runtime type is a . -- By the overloads that include an parameter and that convert either a numeric value to a string or a value to a string. +- By the overloads that include an parameter and that convert either a numeric value to a string or a value to a string. However, any user-defined type that implements can make use of the parameter. @@ -94,10 +94,10 @@ However, any user-defined type that implements can ma Base64 encoding converts binary data to a string. Data expressed as base-64 digits can be easily conveyed over data channels that can only transmit 7-bit characters. The class includes the following methods to support base64 encoding: A set of methods support converting an array of bytes to and from a or to and from an array of Unicode characters consisting of base-64 digit characters. -- , which converts a byte array to a base64-encoded string. -- , which converts a byte array to a base64-encoded character array. -- , which converts a base64-encoded string to a byte array. -- , which converts a base64-encoded character array to a byte array. +- , which converts a byte array to a base64-encoded string. +- , which converts a byte array to a base64-encoded character array. +- , which converts a base64-encoded string to a byte array. +- , which converts a base64-encoded character array to a byte array. ## Other common conversions @@ -113,7 +113,7 @@ You can use other .NET classes to perform some conversions that aren't supported ## Examples -The following example demonstrates some of the conversion methods in the class, including , , and . +The following example demonstrates some of the conversion methods in the class, including , , and . :::code language="csharp" source="./snippets/System/Convert/Overview/csharp/converter.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Convert/Overview/fsharp/converter.fs" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-data-commandbehavior.md b/docs/fundamentals/runtime-libraries/system-data-commandbehavior.md index 7ae5238eb993b..1aa02b5dd588a 100644 --- a/docs/fundamentals/runtime-libraries/system-data-commandbehavior.md +++ b/docs/fundamentals/runtime-libraries/system-data-commandbehavior.md @@ -7,7 +7,7 @@ ms.date: 01/02/2024 [!INCLUDE [context](includes/context.md)] -The `CommandBehavior` values are used by the method of and any implementing classes. +The `CommandBehavior` values are used by the method of and any implementing classes. A bitwise combination of these values may be used. diff --git a/docs/fundamentals/runtime-libraries/system-data-dataset.md b/docs/fundamentals/runtime-libraries/system-data-dataset.md index b78273bfdd0e9..119f8d780a9d1 100644 --- a/docs/fundamentals/runtime-libraries/system-data-dataset.md +++ b/docs/fundamentals/runtime-libraries/system-data-dataset.md @@ -9,9 +9,9 @@ ms.date: 01/02/2024 The class, which is an in-memory cache of data retrieved from a data source, is a major component of the ADO.NET architecture. The consists of a collection of objects that you can relate to each other with objects. You can also enforce data integrity in the by using the and objects. For further details about working with objects, see [DataSets, DataTables, and DataViews](../../framework/data/adonet/dataset-datatable-dataview/index.md). -Whereas objects contain the data, the allows you to navigate though the table hierarchy. The tables are contained in a accessed through the property. When accessing objects, note that they are conditionally case sensitive. For example, if one is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. For more information about working with objects, see [Creating a DataTable](../../framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md). +Whereas objects contain the data, the allows you to navigate though the table hierarchy. The tables are contained in a accessed through the property. When accessing objects, note that they are conditionally case sensitive. For example, if one is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. For more information about working with objects, see [Creating a DataTable](../../framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md). -A can read and write data and schema as XML documents. The data and schema can then be transported across HTTP and used by any application, on any platform that is XML-enabled. You can save the schema as an XML schema with the method, and both schema and data can be saved using the method. To read an XML document that includes both schema and data, use the method. +A can read and write data and schema as XML documents. The data and schema can then be transported across HTTP and used by any application, on any platform that is XML-enabled. You can save the schema as an XML schema with the method, and both schema and data can be saved using the method. To read an XML document that includes both schema and data, use the method. In a typical multiple-tier implementation, the steps for creating and refreshing a , and in turn, updating the original data are to: @@ -19,19 +19,19 @@ In a typical multiple-tier implementation, the steps for creating and refreshing 2. Change the data in individual objects by adding, updating, or deleting objects. -3. Invoke the method to create a second that features only the changes to the data. +3. Invoke the method to create a second that features only the changes to the data. -4. Call the method of the , passing the second as an argument. +4. Call the method of the , passing the second as an argument. -5. Invoke the method to merge the changes from the second into the first. +5. Invoke the method to merge the changes from the second into the first. -6. Invoke the on the . Alternatively, invoke to cancel the changes. +6. Invoke the on the . Alternatively, invoke to cancel the changes. > [!NOTE] > The and objects inherit from , and support the interface for remoting. These are the only ADO.NET objects that can be remoted. > [!NOTE] -> Classes inherited from are not finalized by the garbage collector, because the finalizer has been suppressed in . The derived class can call the method in its constructor to allow the class to be finalized by the garbage collector. +> Classes inherited from are not finalized by the garbage collector, because the finalizer has been suppressed in . The derived class can call the method in its constructor to allow the class to be finalized by the garbage collector. ## Security considerations diff --git a/docs/fundamentals/runtime-libraries/system-data-datatable.md b/docs/fundamentals/runtime-libraries/system-data-datatable.md index e7899a048a54e..7ab25d9281874 100644 --- a/docs/fundamentals/runtime-libraries/system-data-datatable.md +++ b/docs/fundamentals/runtime-libraries/system-data-datatable.md @@ -12,17 +12,17 @@ dev_langs: The class is a central object in the ADO.NET library. Other objects that use include the and the . - object names are conditionally case sensitive. For example, if one is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. A can contain two objects that have the same property value but different property values. For more information about working with objects, see [Creating a DataTable](../../framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md). + object names are conditionally case sensitive. For example, if one is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. A can contain two objects that have the same property value but different property values. For more information about working with objects, see [Creating a DataTable](../../framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md). -If you're creating a programmatically, you must first define its schema by adding objects to the (accessed through the property). For more information about adding objects, see [Adding Columns to a DataTable](../../framework/data/adonet/dataset-datatable-dataview/adding-columns-to-a-datatable.md). +If you're creating a programmatically, you must first define its schema by adding objects to the (accessed through the property). For more information about adding objects, see [Adding Columns to a DataTable](../../framework/data/adonet/dataset-datatable-dataview/adding-columns-to-a-datatable.md). -To add rows to a , you must first use the method to return a new object. The method returns a row with the schema of the , as it is defined by the table's . The maximum number of rows that a can store is 16,777,216. For more information, see [Adding Data to a DataTable](../../framework/data/adonet/dataset-datatable-dataview/adding-data-to-a-datatable.md). +To add rows to a , you must first use the method to return a new object. The method returns a row with the schema of the , as it is defined by the table's . The maximum number of rows that a can store is 16,777,216. For more information, see [Adding Data to a DataTable](../../framework/data/adonet/dataset-datatable-dataview/adding-data-to-a-datatable.md). The also contains a collection of objects that can be used to ensure the integrity of the data. For more information, see [DataTable Constraints](../../framework/data/adonet/dataset-datatable-dataview/datatable-constraints.md). There are many events that can be used to determine when changes are made to a table. These include , , , and . For more information about the events that can be used with a , see [Handling DataTable Events](../../framework/data/adonet/dataset-datatable-dataview/handling-datatable-events.md). -When an instance of is created, some of the read/write properties are set to initial values. For a list of these values, see the constructor. +When an instance of is created, some of the read/write properties are set to initial values. For a list of these values, see the constructor. > [!NOTE] > The and objects inherit from and support the interface for .NET remoting. These are the only ADO.NET objects that you can use for .NET remoting. diff --git a/docs/fundamentals/runtime-libraries/system-datetime-tobinary.md b/docs/fundamentals/runtime-libraries/system-datetime-tobinary.md index 32600214e6b5a..47a83cb06d389 100644 --- a/docs/fundamentals/runtime-libraries/system-datetime-tobinary.md +++ b/docs/fundamentals/runtime-libraries/system-datetime-tobinary.md @@ -11,24 +11,24 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -Use the method to convert the value of the current object to a binary value. Subsequently, use the binary value and the method to recreate the original object. +Use the method to convert the value of the current object to a binary value. Subsequently, use the binary value and the method to recreate the original object. > [!IMPORTANT] -> In some cases, the value returned by the method is not identical to the original value supplied to the method. For more information, see the next section, "Local Time Adjustment". +> In some cases, the value returned by the method is not identical to the original value supplied to the method. For more information, see the next section, "Local Time Adjustment". A structure consists of a private field, which indicates whether the specified time value is based on local time, Coordinated Universal Time (UTC), or neither, concatenated to a private field, which contains the number of 100-nanosecond ticks that specify a date and time. ## Local time adjustment -A local time, which is a Coordinated Universal Time adjusted to the local time zone, is represented by a structure whose property has the value . When restoring a local value from the binary representation that is produced by the method, the method may adjust the recreated value so that it is not equal to the original value. This can occur under the following conditions: +A local time, which is a Coordinated Universal Time adjusted to the local time zone, is represented by a structure whose property has the value . When restoring a local value from the binary representation that is produced by the method, the method may adjust the recreated value so that it is not equal to the original value. This can occur under the following conditions: -- If a local object is serialized in one time zone by the method, and then deserialized in a different time zone by the method, the local time represented by the resulting object is automatically adjusted to the second time zone. +- If a local object is serialized in one time zone by the method, and then deserialized in a different time zone by the method, the local time represented by the resulting object is automatically adjusted to the second time zone. - For example, consider a object that represents a local time of 3 P.M. An application that is executing in the U.S. Pacific Time zone uses the method to convert that object to a binary value. Another application that is executing in the U.S. Eastern Time zone then uses the method to convert the binary value to a new object. The value of the new object is 6 P.M., which represents the same point in time as the original 3 P.M. value, but is adjusted to local time in the Eastern Time zone. + For example, consider a object that represents a local time of 3 P.M. An application that is executing in the U.S. Pacific Time zone uses the method to convert that object to a binary value. Another application that is executing in the U.S. Eastern Time zone then uses the method to convert the binary value to a new object. The value of the new object is 6 P.M., which represents the same point in time as the original 3 P.M. value, but is adjusted to local time in the Eastern Time zone. -- If the binary representation of a local value represents an invalid time in the local time zone of the system on which is called, the time is adjusted so that it is valid. +- If the binary representation of a local value represents an invalid time in the local time zone of the system on which is called, the time is adjusted so that it is valid. - For example, the transition from standard time to daylight saving time occurs in the Pacific Time zone of the United States on March 14, 2010, at 2:00 A.M., when the time advances by one hour, to 3:00 A.M. This hour interval is an invalid time, that is, a time interval that does not exist in this time zone. The following example shows that when a time that falls within this range is converted to a binary value by the method and is then restored by the method, the original value is adjusted to become a valid time. You can determine whether a particular date and time value may be subject to modification by passing it to the method, as the example illustrates. + For example, the transition from standard time to daylight saving time occurs in the Pacific Time zone of the United States on March 14, 2010, at 2:00 A.M., when the time advances by one hour, to 3:00 A.M. This hour interval is an invalid time, that is, a time interval that does not exist in this time zone. The following example shows that when a time that falls within this range is converted to a binary value by the method and is then restored by the method, the original value is adjusted to become a valid time. You can determine whether a particular date and time value may be subject to modification by passing it to the method, as the example illustrates. :::code language="csharp" source="./snippets/System/DateTime/FromBinary/csharp/frombinary1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/DateTime/FromBinary/fsharp/frombinary1.fs" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-datetime-tryparse.md b/docs/fundamentals/runtime-libraries/system-datetime-tryparse.md index 21139625e6b0c..fb170ef74be51 100644 --- a/docs/fundamentals/runtime-libraries/system-datetime-tryparse.md +++ b/docs/fundamentals/runtime-libraries/system-datetime-tryparse.md @@ -9,13 +9,13 @@ ms.date: 01/24/2024 The method parses a string that can contain date, time, and time zone information. It is similar to the method, except that the method does not throw an exception if the conversion fails. -This method attempts to ignore unrecognized data and parse the input string (`s`) completely. If `s` contains a time but no date, the method by default substitutes the current date or, if `styles` includes the flag, it substitutes `DateTime.Date.MinValue`. If `s` contains a date but no time, 12:00 midnight is used as the default time. If a date is present but its year component consists of only two digits, it is converted to a year in the `provider` parameter's current calendar based on the value of the property. Any leading, inner, or trailing white space characters in `s` are ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000). +This method attempts to ignore unrecognized data and parse the input string (`s`) completely. If `s` contains a time but no date, the method by default substitutes the current date or, if `styles` includes the flag, it substitutes `DateTime.Date.MinValue`. If `s` contains a date but no time, 12:00 midnight is used as the default time. If a date is present but its year component consists of only two digits, it is converted to a year in the `provider` parameter's current calendar based on the value of the property. Any leading, inner, or trailing white space characters in `s` are ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000). Specific valid formats for date and time elements, as well as the names and symbols used in dates and times, are defined by the `provider` parameter, which can be any of the following: -- A object that represents the culture whose formatting is used in the `s` parameter. The object returned by the property defines the formatting used in `s`. +- A object that represents the culture whose formatting is used in the `s` parameter. The object returned by the property defines the formatting used in `s`. - A object that defines the formatting used in `s`. -- A custom implementation. Its method returns a object that defines the formatting used in `s`. +- A custom implementation. Its method returns a object that defines the formatting used in `s`. If `provider` is `null`, the current culture is used. @@ -25,7 +25,7 @@ The `styles` parameter defines the precise interpretation of the parsed string a |DateTimeStyles member|Description| |---------------------------|-----------------| -||Parses `s` and, if necessary, converts it to UTC. If `s` includes a time zone offset, or if `s` contains no time zone information but `styles` includes the flag, the method parses the string, calls to convert the returned value to UTC, and sets the property to . If `s` indicates that it represents UTC, or if `s` does not contain time zone information but `styles` includes the flag, the method parses the string, performs no time zone conversion on the returned value, and sets the property to . In all other cases, the flag has no effect.| +||Parses `s` and, if necessary, converts it to UTC. If `s` includes a time zone offset, or if `s` contains no time zone information but `styles` includes the flag, the method parses the string, calls to convert the returned value to UTC, and sets the property to . If `s` indicates that it represents UTC, or if `s` does not contain time zone information but `styles` includes the flag, the method parses the string, performs no time zone conversion on the returned value, and sets the property to . In all other cases, the flag has no effect.| ||Although valid, this value is ignored. Inner white space is permitted in the date and time elements of `s`.| ||Although valid, this value is ignored. Leading white space is permitted in the date and time elements of `s`.| ||Although valid, this value is ignored. Trailing white space is permitted in the date and time elements of `s`.| @@ -44,6 +44,6 @@ This behavior can be overridden by using the method instead of the method to improve the probability that the parse operation will succeed. A custom culture date and time string can be complicated and difficult to parse. The method attempts to parse a string with several implicit parse patterns, all of which might fail. In contrast, the method requires you to explicitly designate one or more exact parse patterns that are likely to succeed. +If you parse a date and time string generated for a custom culture, use the method instead of the method to improve the probability that the parse operation will succeed. A custom culture date and time string can be complicated and difficult to parse. The method attempts to parse a string with several implicit parse patterns, all of which might fail. In contrast, the method requires you to explicitly designate one or more exact parse patterns that are likely to succeed. For more information about custom cultures, see the class. diff --git a/docs/fundamentals/runtime-libraries/system-datetime.md b/docs/fundamentals/runtime-libraries/system-datetime.md index 61995207a288d..518bb5db52ec2 100644 --- a/docs/fundamentals/runtime-libraries/system-datetime.md +++ b/docs/fundamentals/runtime-libraries/system-datetime.md @@ -109,14 +109,14 @@ You can assign the object a date and time value returned ### Parse a string that represents a DateTime -The , , , and methods all convert a string to its equivalent date and time value. The following examples use the and methods to parse a string and convert it to a value. The second format uses a form supported by the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) standard for a representing date and time in string format. This standard representation is often used to transfer date information in web services. +The , , , and methods all convert a string to its equivalent date and time value. The following examples use the and methods to parse a string and convert it to a value. The second format uses a form supported by the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) standard for a representing date and time in string format. This standard representation is often used to transfer date information in web services. :::code language="vb" source="./snippets/System/DateTime/Overview/vb/Instantiation.vb" id="Snippet4"::: :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Instantiation.cs" id="Snippet4"::: :::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Instantiation.fs" id="Snippet4"::: -The and methods indicate whether a string is a valid representation of a value and, if it is, performs the conversion. +The and methods indicate whether a string is a valid representation of a value and, if it is, performs the conversion. ### Language-specific syntax for Visual Basic @@ -129,35 +129,35 @@ The following Visual Basic statement initializes a new va Internally, all values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. The actual value is independent of the way in which that value appears when displayed. The appearance of a value is the result of a formatting operation that converts a value to its string representation. -The appearance of date and time values is dependent on culture, international standards, application requirements, and personal preference. The structure offers flexibility in formatting date and time values through overloads of . The default method returns the string representation of a date and time value using the current culture's short date and long time pattern. The following example uses the default method. It displays the date and time using the short date and long time pattern for the current culture. The en-US culture is the current culture on the computer on which the example was run. +The appearance of date and time values is dependent on culture, international standards, application requirements, and personal preference. The structure offers flexibility in formatting date and time values through overloads of . The default method returns the string representation of a date and time value using the current culture's short date and long time pattern. The following example uses the default method. It displays the date and time using the short date and long time pattern for the current culture. The en-US culture is the current culture on the computer on which the example was run. :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/StringFormat.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/StringFormat.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/DateTime/Overview/vb/StringFormat.vb" id="Snippet1"::: -You may need to format dates in a specific culture to support web scenarios where the server may be in a different culture from the client. You specify the culture using the method to create the short date and long time representation in a specific culture. The following example uses the method to display the date and time using the short date and long time pattern for the fr-FR culture. +You may need to format dates in a specific culture to support web scenarios where the server may be in a different culture from the client. You specify the culture using the method to create the short date and long time representation in a specific culture. The following example uses the method to display the date and time using the short date and long time pattern for the fr-FR culture. :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/StringFormat.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/StringFormat.fs" id="Snippet2"::: :::code language="vb" source="./snippets/System/DateTime/Overview/vb/StringFormat.vb" id="Snippet2"::: -Other applications may require different string representations of a date. The method returns the string representation defined by a standard or custom format specifier using the formatting conventions of the current culture. The following example uses the method to display the full date and time pattern for the en-US culture, the current culture on the computer on which the example was run. +Other applications may require different string representations of a date. The method returns the string representation defined by a standard or custom format specifier using the formatting conventions of the current culture. The following example uses the method to display the full date and time pattern for the en-US culture, the current culture on the computer on which the example was run. :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/StringFormat.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/StringFormat.fs" id="Snippet3"::: :::code language="vb" source="./snippets/System/DateTime/Overview/vb/StringFormat.vb" id="Snippet3"::: -Finally, you can specify both the culture and the format using the method. The following example uses the method to display the full date and time pattern for the fr-FR culture. +Finally, you can specify both the culture and the format using the method. The following example uses the method to display the full date and time pattern for the fr-FR culture. :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/StringFormat.cs" id="Snippet4"::: :::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/StringFormat.fs" id="Snippet4"::: :::code language="vb" source="./snippets/System/DateTime/Overview/vb/StringFormat.vb" id="Snippet4"::: -The overload can also be used with a custom format string to specify other formats. The following example shows how to format a string using the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) standard format often used for web services. The Iso 8601 format does not have a corresponding standard format string. +The overload can also be used with a custom format string to specify other formats. The following example shows how to format a string using the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) standard format often used for web services. The Iso 8601 format does not have a corresponding standard format string. :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/StringFormat.cs" id="Snippet5"::: @@ -174,28 +174,28 @@ Parsing converts the string representation of a date and time to a or method to convert a string from one of the common date and time formats used by a culture to a value. The following example shows how you can use to convert date strings in different culture-specific formats to a value. It changes the current culture to English (United Kingdom) and calls the method to generate an array of date and time strings. It then passes each element in the array to the method. The output from the example shows the parsing method was able to successfully convert each of the culture-specific date and time strings. +You use the or method to convert a string from one of the common date and time formats used by a culture to a value. The following example shows how you can use to convert date strings in different culture-specific formats to a value. It changes the current culture to English (United Kingdom) and calls the method to generate an array of date and time strings. It then passes each element in the array to the method. The output from the example shows the parsing method was able to successfully convert each of the culture-specific date and time strings. :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Parsing.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Parsing.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/DateTime/Overview/vb/Parsing.vb" id="Snippet1"::: -You use the and methods to convert a string that must match a particular format or formats to a value. You specify one or more date and time format strings as a parameter to the parsing method. The following example uses the method to convert strings that must be either in a "yyyyMMdd" format or a "HHmmss" format to values. +You use the and methods to convert a string that must match a particular format or formats to a value. You specify one or more date and time format strings as a parameter to the parsing method. The following example uses the method to convert strings that must be either in a "yyyyMMdd" format or a "HHmmss" format to values. :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Parsing.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Parsing.fs" id="Snippet2"::: :::code language="vb" source="./snippets/System/DateTime/Overview/vb/Parsing.vb" id="Snippet2"::: -One common use for is to convert a string representation from a web service, usually in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) standard format. The following code shows the correct format string to use: +One common use for is to convert a string representation from a web service, usually in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) standard format. The following code shows the correct format string to use: :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Parsing.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Parsing.fs" id="Snippet3"::: :::code language="vb" source="./snippets/System/DateTime/Overview/vb/Parsing.vb" id="Snippet3"::: -If a string cannot be parsed, the and methods throw an exception. The and methods return a value that indicates whether the conversion succeeded or failed. You should use the or methods in scenarios where performance is important. The parsing operation for date and time strings tends to have a high failure rate, and exception handling is expensive. Use these methods if strings are input by users or coming from an unknown source. +If a string cannot be parsed, the and methods throw an exception. The and methods return a value that indicates whether the conversion succeeded or failed. You should use the or methods in scenarios where performance is important. The parsing operation for date and time strings tends to have a high failure rate, and exception handling is expensive. Use these methods if strings are input by users or coming from an unknown source. For more information about parsing date and time values, see [Parsing Date and Time Strings](../../standard/base-types/parsing-datetime.md). @@ -216,7 +216,7 @@ If the property of a object i The property expresses date and time values in units of one ten-millionth of a second. The property returns the thousandths of a second in a date and time value. Using repeated calls to the property to measure elapsed time is dependent on the system clock. The system clock on Windows 7 and Windows 8 systems has a resolution of approximately 15 milliseconds. This resolution affects small time intervals less than 100 milliseconds. -The following example illustrates the dependence of current date and time values on the resolution of the system clock. In the example, an outer loop repeats 20 times, and an inner loop serves to delay the outer loop. If the value of the outer loop counter is 10, a call to the method introduces a five-millisecond delay. The following example shows the number of milliseconds returned by the `DateTime.Now.Milliseconds` property changes only after the call to . +The following example illustrates the dependence of current date and time values on the resolution of the system clock. In the example, an outer loop repeats 20 times, and an inner loop serves to delay the outer loop. If the value of the outer loop counter is 10, a call to the method introduces a five-millisecond delay. The following example shows the number of milliseconds returned by the `DateTime.Now.Milliseconds` property changes only after the call to . :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Resolution.cs" id="Snippet1"::: @@ -225,11 +225,11 @@ The following example illustrates the dependence of current date and time values ## DateTime operations -A calculation using a structure, such as or , does not modify the value of the structure. Instead, the calculation returns a new structure whose value is the result of the calculation. +A calculation using a structure, such as or , does not modify the value of the structure. Instead, the calculation returns a new structure whose value is the result of the calculation. Conversion operations between time zones (such as between UTC and local time, or between one time zone and another) take daylight saving time into account, but arithmetic and comparison operations do not. -The structure itself offers limited support for converting from one time zone to another. You can use the method to convert UTC to local time, or you can use the method to convert from local time to UTC. However, a full set of time zone conversion methods is available in the class. You convert the time in any one of the world's time zones to the time in any other time zone using these methods. +The structure itself offers limited support for converting from one time zone to another. You can use the method to convert UTC to local time, or you can use the method to convert from local time to UTC. However, a full set of time zone conversion methods is available in the class. You convert the time in any one of the world's time zones to the time in any other time zone using these methods. Calculations and comparisons of objects are meaningful only if the objects represent times in the same time zone. You can use a object to represent a value's time zone, although the two are loosely coupled. A object does not have a property that returns an object that represents that date and time value's time zone. The property indicates if a `DateTime` represents UTC, local time, or is unspecified. In a time zone-aware application, you must rely on some external mechanism to determine the time zone in which a object was created. You could use a structure that wraps both the value and the object that represents the value's time zone. For details on using UTC in calculations and comparisons with values, see [Performing Arithmetic Operations with Dates and Times](../../standard/datetime/performing-arithmetic-operations.md). @@ -259,7 +259,7 @@ The .NET Class Library includes a number of calendar classes, all of which are d [!INCLUDE[japanese-era-note](./includes/calendar-era.md)] -Each culture uses a default calendar defined by its read-only property. Each culture may support one or more calendars defined by its read-only property. The calendar currently used by a specific object is defined by its property. It must be one of the calendars found in the array. +Each culture uses a default calendar defined by its read-only property. Each culture may support one or more calendars defined by its read-only property. The calendar currently used by a specific object is defined by its property. It must be one of the calendars found in the array. A culture's current calendar is used in all formatting operations for that culture. For example, the default calendar of the Thai Buddhist culture is the Thai Buddhist Era calendar, which is represented by the class. When a object that represents the Thai Buddhist culture is used in a date and time formatting operation, the Thai Buddhist Era calendar is used by default. The Gregorian calendar is used only if the culture's property is changed, as the following example shows: @@ -275,7 +275,7 @@ A culture's current calendar is also used in all parsing operations for that cul :::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Calendar.fs" id="Snippet2"::: :::code language="vb" source="./snippets/System/DateTime/Overview/vb/Calendar.vb" id="Snippet2"::: -You instantiate a value using the date and time elements (number of the year, month, and day) of a specific calendar by calling a [DateTime constructor](xref:System.DateTime.%23ctor%2A) that includes a `calendar` parameter and passing it a object that represents that calendar. The following example uses the date and time elements from the calendar. +You instantiate a value using the date and time elements (number of the year, month, and day) of a specific calendar by calling a [DateTime constructor](xref:System.DateTime.%23ctor*) that includes a `calendar` parameter and passing it a object that represents that calendar. The following example uses the date and time elements from the calendar. :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Calendar.cs" id="Snippet3"::: @@ -284,14 +284,14 @@ You instantiate a value using the date and time elements constructors that do not include a `calendar` parameter assume that the date and time elements are expressed as units in the Gregorian calendar. -All other properties and methods use the Gregorian calendar. For example, the property returns the year in the Gregorian calendar, and the method assumes that the `year` parameter is a year in the Gregorian calendar. Each member that uses the Gregorian calendar has a corresponding member of the class that uses a specific calendar. For example, the method returns the year in a specific calendar, and the method interprets the `year` parameter as a year number in a specific calendar. The following example uses both the and the corresponding members of the class. +All other properties and methods use the Gregorian calendar. For example, the property returns the year in the Gregorian calendar, and the method assumes that the `year` parameter is a year in the Gregorian calendar. Each member that uses the Gregorian calendar has a corresponding member of the class that uses a specific calendar. For example, the method returns the year in a specific calendar, and the method interprets the `year` parameter as a year number in a specific calendar. The following example uses both the and the corresponding members of the class. :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Calendar.cs" id="Snippet4"::: :::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Calendar.fs" id="Snippet4"::: :::code language="vb" source="./snippets/System/DateTime/Overview/vb/Calendar.vb" id="Snippet4"::: -The structure includes a property that returns the day of the week in the Gregorian calendar. It does not include a member that allows you to retrieve the week number of the year. To retrieve the week of the year, call the individual calendar's method. The following example provides an illustration. +The structure includes a property that returns the day of the week in the Gregorian calendar. It does not include a member that allows you to retrieve the week number of the year. To retrieve the week of the year, call the individual calendar's method. The following example provides an illustration. :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Calendar.cs" id="Snippet5"::: @@ -314,7 +314,7 @@ You must ensure that the routine that restores the values To successfully restore values that are persisted as strings, follow these rules: -- Make the same assumptions about culture-specific formatting when you restore the string as when you persisted it. To ensure that a string can be restored on a system whose current culture is different from the culture of the system it was saved on, call the overload to save the string by using the conventions of the invariant culture. Call the or overload to restore the string by using the conventions of the invariant culture. Never use the , , or overloads, which use the conventions of the current culture. +- Make the same assumptions about culture-specific formatting when you restore the string as when you persisted it. To ensure that a string can be restored on a system whose current culture is different from the culture of the system it was saved on, call the overload to save the string by using the conventions of the invariant culture. Call the or overload to restore the string by using the conventions of the invariant culture. Never use the , , or overloads, which use the conventions of the current culture. - If the date represents a single moment of time, ensure that it represents the same moment in time when it's restored, even on a different time zone. Convert the value to Coordinated Universal Time (UTC) before saving it or use . @@ -326,13 +326,13 @@ The most common error made when persisting values as stri To round-trip values successfully, follow these steps: -1. If the values represent single moments of time, convert them from the local time to UTC by calling the method. -1. Convert the dates to their string representations by calling the or overload. Use the formatting conventions of the invariant culture by specifying as the `provider` argument. Specify that the value should round-trip by using the "O" or "R" standard format string. +1. If the values represent single moments of time, convert them from the local time to UTC by calling the method. +1. Convert the dates to their string representations by calling the or overload. Use the formatting conventions of the invariant culture by specifying as the `provider` argument. Specify that the value should round-trip by using the "O" or "R" standard format string. To restore the persisted values without data loss, follow these steps: -1. Parse the data by calling the or overload. Specify as the `provider` argument, and use the same standard format string you used for the `format` argument during conversion. Include the value in the `styles` argument. -1. If the values represent single moments in time, call the method to convert the parsed date from UTC to local time. +1. Parse the data by calling the or overload. Specify as the `provider` argument, and use the same standard format string you used for the `format` argument during conversion. Include the value in the `styles` argument. +1. If the values represent single moments in time, call the method to convert the parsed date from UTC to local time. The following example uses the invariant culture and the "O" standard format string to ensure that values saved and restored represent the same moment in time regardless of the system, culture, or time zone of the source and target systems. @@ -346,13 +346,13 @@ You can persist a date and time as an value that represents To persist a value as an integer: -1. If the values represent single moments in time, convert them to UTC by calling the method. +1. If the values represent single moments in time, convert them to UTC by calling the method. 1. Retrieve the number of ticks represented by the value from its property. To restore a value that has been persisted as an integer: -1. Instantiate a new object by passing the value to the constructor. -1. If the value represents a single moment in time, convert it from UTC to the local time by calling the method. +1. Instantiate a new object by passing the value to the constructor. +1. If the value represents a single moment in time, convert it from UTC to the local time by calling the method. The following example persists an array of values as integers on a system in the U.S. Pacific Time zone. It restores it on a system in the UTC zone. The file that contains the integers includes an value that indicates the total number of values that immediately follow it. @@ -372,7 +372,7 @@ The following example uses the cla :::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Persistence.cs" id="Snippet4"::: :::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Persistence.fs" id="Snippet4"::: -The previous example doesn't include time information. If a value represents a moment in time and is expressed as a local time, convert it from local time to UTC before serializing it by calling the method. After you deserialize it, convert it from UTC to local time by calling the method. +The previous example doesn't include time information. If a value represents a moment in time and is expressed as a local time, convert it from local time to UTC before serializing it by calling the method. After you deserialize it, convert it from UTC to local time by calling the method. ## DateTime vs. TimeSpan diff --git a/docs/fundamentals/runtime-libraries/system-decimal.md b/docs/fundamentals/runtime-libraries/system-decimal.md index c28d015d4d3eb..a36913507d7f9 100644 --- a/docs/fundamentals/runtime-libraries/system-decimal.md +++ b/docs/fundamentals/runtime-libraries/system-decimal.md @@ -17,7 +17,7 @@ The value type represents decimal numbers ranging from pos :::code language="fsharp" source="./snippets/System/Decimal/Overview/fsharp/DecimalDivision_46630_1.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/Decimal/Overview/vb/DecimalDivision_46630_1.vb" id="Snippet1"::: -When the result of the division and multiplication is passed to the method, the result suffers no loss of precision, as the following code shows. +When the result of the division and multiplication is passed to the method, the result suffers no loss of precision, as the following code shows. :::code language="csharp" source="./snippets/System/Decimal/Overview/csharp/DecimalDivision_46630_1.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/Decimal/Overview/fsharp/DecimalDivision_46630_1.fs" id="Snippet2"::: @@ -25,9 +25,9 @@ When the result of the division and multiplication is passed to the value the form, ((-296 to 296) / 10(0 to 28)), where -(296-1) is equal to , and 296-1 is equal to . For more information about the binary representation of values and an example, see the constructor and the method. +The binary representation of a `Decimal` value is 128-bits consisting of a 96-bit integer number, and a 32-bit set of flags representing things such as the sign and scaling factor used to specify what portion of it is a decimal fraction. Therefore, the binary representation of a value the form, ((-296 to 296) / 10(0 to 28)), where -(296-1) is equal to , and 296-1 is equal to . For more information about the binary representation of values and an example, see the constructor and the method. -The scaling factor also preserves any trailing zeros in a number. Trailing zeros do not affect the value of a number in arithmetic or comparison operations. However, trailing zeros might be revealed by the method if an appropriate format string is applied. +The scaling factor also preserves any trailing zeros in a number. Trailing zeros do not affect the value of a number in arithmetic or comparison operations. However, trailing zeros might be revealed by the method if an appropriate format string is applied. ## Conversion considerations @@ -41,9 +41,9 @@ Conversions from or to type supports standard mathematical operations such as addition, subtraction, division, multiplication, and unary negation. You can also work directly with the binary representation of a value by calling the method. +The type supports standard mathematical operations such as addition, subtraction, division, multiplication, and unary negation. You can also work directly with the binary representation of a value by calling the method. -To compare two values, you can use the standard numeric comparison operators, or you can call the or method. +To compare two values, you can use the standard numeric comparison operators, or you can call the or method. You can also call the members of the class to perform a wide range of numeric operations, including getting the absolute value of a number, determining the maximum or minimum value of two values, getting the sign of a number, and rounding a number. diff --git a/docs/fundamentals/runtime-libraries/system-delegate-createdelegate.md b/docs/fundamentals/runtime-libraries/system-delegate-createdelegate.md index 4d0a0bcbd9f81..bcbac4cdb30e3 100644 --- a/docs/fundamentals/runtime-libraries/system-delegate-createdelegate.md +++ b/docs/fundamentals/runtime-libraries/system-delegate-createdelegate.md @@ -11,7 +11,7 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The methods create a delegate of a specified type. +The methods create a delegate of a specified type. ## method @@ -25,10 +25,10 @@ The second code example demonstrates compatible parameter types and return types #### Example 1 -The following code example demonstrates the two ways a delegate can be created using this overload of the method. +The following code example demonstrates the two ways a delegate can be created using this overload of the method. > [!NOTE] -> There are two overloads of the method that specify a but not a first argument; their functionality is the same except that one allows you to specify whether to throw on failure to bind, and the other always throws. This code example uses both overloads. +> There are two overloads of the method that specify a but not a first argument; their functionality is the same except that one allows you to specify whether to throw on failure to bind, and the other always throws. This code example uses both overloads. The example declares a class `C` with a static method `M2` and an instance method `M1`, and two delegate types: `D1` takes an instance of `C` and a string, and `D2` takes a string. @@ -112,10 +112,10 @@ For example, a delegate with a parameter of type overload is that any given delegate can represent four different combinations of method signature and method kind (static versus instance). Consider a delegate type `D` with one argument of type `C`. The following describes the methods `D` can represent, ignoring the return type since it must match in all cases: -- `D` can represent any instance method that has exactly one argument of type `C`, regardless of what type the instance method belongs to. When is called, `firstArgument` is an instance of the type `method` belongs to, and the resulting delegate is said to be closed over that instance. (Trivially, `D` can also be closed over a null reference if `firstArgument` is a null reference.) +- `D` can represent any instance method that has exactly one argument of type `C`, regardless of what type the instance method belongs to. When is called, `firstArgument` is an instance of the type `method` belongs to, and the resulting delegate is said to be closed over that instance. (Trivially, `D` can also be closed over a null reference if `firstArgument` is a null reference.) -- `D` can represent an instance method of `C` that has no arguments. When is called, `firstArgument` is a null reference. The resulting delegate represents an open instance method, and an instance of `C` must be supplied each time it is invoked. +- `D` can represent an instance method of `C` that has no arguments. When is called, `firstArgument` is a null reference. The resulting delegate represents an open instance method, and an instance of `C` must be supplied each time it is invoked. -- `D` can represent a static method that takes one argument of type `C`, and that method can belong to any type. When is called, `firstArgument` is a null reference. The resulting delegate represents an open static method, and an instance of `C` must be supplied each time it is invoked. +- `D` can represent a static method that takes one argument of type `C`, and that method can belong to any type. When is called, `firstArgument` is a null reference. The resulting delegate represents an open static method, and an instance of `C` must be supplied each time it is invoked. -- `D` can represent a static method that belongs to type `F` and has two arguments, of type `F` and type `C`. When is called, `firstArgument` is an instance of `F`. The resulting delegate represents a static method that is closed over that instance of `F`. Note that in the case where `F` and `C` are the same type, the static method has two arguments of that type. (In this case, `D` is closed over a null reference if `firstArgument` is a null reference.) +- `D` can represent a static method that belongs to type `F` and has two arguments, of type `F` and type `C`. When is called, `firstArgument` is an instance of `F`. The resulting delegate represents a static method that is closed over that instance of `F`. Note that in the case where `F` and `C` are the same type, the static method has two arguments of that type. (In this case, `D` is closed over a null reference if `firstArgument` is a null reference.) diff --git a/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md b/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md index f5fa7671c8c6d..13a375f29f12e 100644 --- a/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md +++ b/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md @@ -10,7 +10,7 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The class is intended to be inherited by a user class that provides specific events to be used for event tracing. The methods are called to log the events. +The class is intended to be inherited by a user class that provides specific events to be used for event tracing. The methods are called to log the events. The basic functionality of is sufficient for most applications. If you want more control over the event metadata that's created, you can apply the attribute to the methods. For advanced event source applications, it is possible to intercept the commands being sent to the derived event source and change the filtering, or to cause actions (such as dumping a data structure) to be performed by the inheritor. An event source can be activated in-process using and out-of-process using EventPipe-based tools such as `dotnet-trace` or Event Tracing for Windows (ETW) based tools like `PerfView` or `Logman`. It is also possible to programmatically control and intercept the data dispatcher. The class provides additional functionality. diff --git a/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventwritteneventargs.md b/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventwritteneventargs.md index a0a3f9675260f..bd552081af4dc 100644 --- a/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventwritteneventargs.md +++ b/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventwritteneventargs.md @@ -7,9 +7,9 @@ ms.date: 12/31/2023 [!INCLUDE [context](includes/context.md)] -The class provides data for the callback. +The class provides data for the callback. -Whenever an event is dispatched to an , the callback method is invoked. It is passed an `EventWrittenEventArgs` instance that contains information associated with the event. All property values of the `EventWrittenEventArgs` class are valid only during the callback. +Whenever an event is dispatched to an , the callback method is invoked. It is passed an `EventWrittenEventArgs` instance that contains information associated with the event. All property values of the `EventWrittenEventArgs` class are valid only during the callback. The following sections contain additional information about individual `EventWrittenEventArgs` properties. diff --git a/docs/fundamentals/runtime-libraries/system-double-compareto.md b/docs/fundamentals/runtime-libraries/system-double-compareto.md index e45ef7bb7962f..38e95286e1887 100644 --- a/docs/fundamentals/runtime-libraries/system-double-compareto.md +++ b/docs/fundamentals/runtime-libraries/system-double-compareto.md @@ -13,21 +13,21 @@ dev_langs: ## method -Values must be identical to be considered equal. Particularly when floating-point values depend on multiple mathematical operations, it is common for them to lose precision and for their values to be nearly identical except for their least significant digits. Because of this, the return value of the method at times may seem surprising. For example, multiplication by a particular value followed by division by the same value should produce the original value. In the following example, however, the computed value turns out to be greater than the original value. Showing all significant digits of the two values by using the "R" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) indicates that the computed value differs from the original value in its least significant digits. For information on handling such comparisons, see the Remarks section of the method. +Values must be identical to be considered equal. Particularly when floating-point values depend on multiple mathematical operations, it is common for them to lose precision and for their values to be nearly identical except for their least significant digits. Because of this, the return value of the method at times may seem surprising. For example, multiplication by a particular value followed by division by the same value should produce the original value. In the following example, however, the computed value turns out to be greater than the original value. Showing all significant digits of the two values by using the "R" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) indicates that the computed value differs from the original value in its least significant digits. For information on handling such comparisons, see the Remarks section of the method. :::code language="csharp" source="./snippets/System/Double/CompareTo/csharp/compareto2.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Double/CompareTo/fsharp/compareto2.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/Double/CompareTo/vb/compareto2.vb" id="Snippet1"::: -This method implements the interface and performs slightly better than the method because it does not have to convert the `value` parameter to an object. +This method implements the interface and performs slightly better than the method because it does not have to convert the `value` parameter to an object. -Note that, although an object whose value is is not considered equal to another object whose value is (even itself), the interface requires that `A.CompareTo(A)` return zero. +Note that, although an object whose value is is not considered equal to another object whose value is (even itself), the interface requires that `A.CompareTo(A)` return zero. ## method The `value` parameter must be `null` or an instance of `Double`; otherwise, an exception is thrown. Any instance of , regardless of its value, is considered greater than `null`. -Values must be identical to be considered equal. Particularly when floating-point values depend on multiple mathematical operations, it is common for them to lose precision and for their values to be nearly identical except for their least significant digits. Because of this, the return value of the method at times may seem surprising. For example, multiplication by a particular value followed by division by the same value should produce the original value. In the following example, however, the computed value turns out to be greater than the original value. Showing all significant digits of the two values by using the "R" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) indicates that the computed value differs from the original value in its least significant digits. For information on handling such comparisons, see the Remarks section of the method. +Values must be identical to be considered equal. Particularly when floating-point values depend on multiple mathematical operations, it is common for them to lose precision and for their values to be nearly identical except for their least significant digits. Because of this, the return value of the method at times may seem surprising. For example, multiplication by a particular value followed by division by the same value should produce the original value. In the following example, however, the computed value turns out to be greater than the original value. Showing all significant digits of the two values by using the "R" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) indicates that the computed value differs from the original value in its least significant digits. For information on handling such comparisons, see the Remarks section of the method. :::code language="csharp" source="./snippets/System/Double/CompareTo/csharp/compareto3.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/Double/CompareTo/fsharp/compareto3.fs" id="Snippet2"::: @@ -37,7 +37,7 @@ This method is implemented to support the interface. N ## Widening conversions -Depending on your programming language, it might be possible to code a method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. +Depending on your programming language, it might be possible to code a method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. For example, suppose the instance type is and the parameter type is . The Microsoft C# compiler generates instructions to represent the value of the parameter as a object, then generates a method that compares the values of the instance and the widened representation of the parameter. diff --git a/docs/fundamentals/runtime-libraries/system-double-equals.md b/docs/fundamentals/runtime-libraries/system-double-equals.md index 7a4517747b8e5..40e6ecbcdc9d1 100644 --- a/docs/fundamentals/runtime-libraries/system-double-equals.md +++ b/docs/fundamentals/runtime-libraries/system-double-equals.md @@ -9,11 +9,11 @@ dev_langs: --- # System.Double.Equals method -Th method implements the interface, and performs slightly better than because it doesn't have to convert the `obj` parameter to an object. +Th method implements the interface, and performs slightly better than because it doesn't have to convert the `obj` parameter to an object. ## Widening conversions -Depending on your programming language, it might be possible to code a method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. +Depending on your programming language, it might be possible to code a method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. For example, suppose the instance type is and the parameter type is . The Microsoft C# compiler generates instructions to represent the value of the parameter as a object, then generates a method that compares the values of the instance and the widened representation of the parameter. @@ -21,7 +21,7 @@ Consult your programming language's documentation to determine if its compiler p ## Precision in comparisons -The method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. The following example reports that the value .333333 and the value returned by dividing 1 by 3 are unequal. +The method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. The following example reports that the value .333333 and the value returned by dividing 1 by 3 are unequal. :::code language="csharp" source="./snippets/System/Double/Epsilon/csharp/Equals_25051.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Double/Epsilon/fsharp/Equals_25051.fs" id="Snippet1"::: @@ -36,7 +36,7 @@ Rather than comparing for equality, one technique involves defining an acceptabl > [!NOTE] > Because defines the minimum expression of a positive value whose range is near zero, the margin of difference between two similar values must be greater than . Typically, it is many times greater than . Because of this, we recommend that you **don't** use when comparing values for equality. -A second technique involves comparing the difference between two floating-point numbers with some absolute value. If the difference is less than or equal to that absolute value, the numbers are equal. If it's greater, the numbers are not equal. One alternative is to arbitrarily select an absolute value. That's problematic, however, because an acceptable margin of difference depends on the magnitude of the values. A second alternative takes advantage of a design feature of the floating-point format: The difference between the integer representation of two floating-point values indicates the number of possible floating-point values that separates them. For example, the difference between 0.0 and is 1, because is the smallest representable value when working with a whose value is zero. The following example uses this technique to compare .33333 and 1/3, which are the two values that the previous code example with the method found to be unequal. The example uses the method to convert a double-precision floating-point value to its integer representation. The example declares the values as equal if there are no possible floating-point values between their integer representations. +A second technique involves comparing the difference between two floating-point numbers with some absolute value. If the difference is less than or equal to that absolute value, the numbers are equal. If it's greater, the numbers are not equal. One alternative is to arbitrarily select an absolute value. That's problematic, however, because an acceptable margin of difference depends on the magnitude of the values. A second alternative takes advantage of a design feature of the floating-point format: The difference between the integer representation of two floating-point values indicates the number of possible floating-point values that separates them. For example, the difference between 0.0 and is 1, because is the smallest representable value when working with a whose value is zero. The following example uses this technique to compare .33333 and 1/3, which are the two values that the previous code example with the method found to be unequal. The example uses the method to convert a double-precision floating-point value to its integer representation. The example declares the values as equal if there are no possible floating-point values between their integer representations. :::code language="csharp" source="./snippets/System/Double/Equals/csharp/equalsabs1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Double/Equals/fsharp/equalsabs1.fs" id="Snippet1"::: @@ -51,4 +51,4 @@ The precision of floating-point numbers beyond the documented precision is speci ## NaN -If two values are tested for equality by calling the method, the method returns `true`. However, if two values are tested for equality by using the *equality operator*, the operator returns `false`. When you want to determine whether the value of a is not a number (NaN), an alternative is to call the method. +If two values are tested for equality by calling the method, the method returns `true`. However, if two values are tested for equality by using the *equality operator*, the operator returns `false`. When you want to determine whether the value of a is not a number (NaN), an alternative is to call the method. diff --git a/docs/fundamentals/runtime-libraries/system-double.md b/docs/fundamentals/runtime-libraries/system-double.md index a925bb4e6e208..e69370b89961d 100644 --- a/docs/fundamentals/runtime-libraries/system-double.md +++ b/docs/fundamentals/runtime-libraries/system-double.md @@ -45,7 +45,7 @@ The limited precision of a floating-point number has several consequences: :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/precisionlist3.fs" id="Snippet6"::: :::code language="vb" source="./snippets/System/Double/Overview/vb/precisionlist3.vb" id="Snippet6"::: - If you change the format items in the statement from `{0}` and `{1}` to `{0:R}` and `{1:R}` to display all significant digits of the two values, it is clear that the two values are unequal because of a loss of precision during the addition operations. In this case, the issue can be resolved by calling the method to round the values to the desired precision before performing the comparison. + If you change the format items in the statement from `{0}` and `{1}` to `{0:R}` and `{1:R}` to display all significant digits of the two values, it is clear that the two values are unequal because of a loss of precision during the addition operations. In this case, the issue can be resolved by calling the method to round the values to the desired precision before performing the comparison. - A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used, because the binary floating-point number might not equal the decimal number. A previous example illustrated this by displaying the result of multiplying .1 by 10 and adding .1 times. @@ -67,9 +67,9 @@ The limited precision of a floating-point number has several consequences: :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/precisionlist1.fs" id="Snippet5"::: :::code language="vb" source="./snippets/System/Double/Overview/vb/precisionlist1.vb" id="Snippet5"::: - To avoid this problem, use either the in place of the data type, or use the method so that both values have the same precision. + To avoid this problem, use either the in place of the data type, or use the method so that both values have the same precision. -In addition, the result of arithmetic and assignment operations with values may differ slightly by platform because of the loss of precision of the type. For example, the result of assigning a literal value may differ in the 32-bit and 64-bit versions of .NET. The following example illustrates this difference when the literal value -4.42330604244772E-305 and a variable whose value is -4.42330604244772E-305 are assigned to a variable. Note that the result of the method in this case does not suffer from a loss of precision. +In addition, the result of arithmetic and assignment operations with values may differ slightly by platform because of the loss of precision of the type. For example, the result of assigning a literal value may differ in the 32-bit and 64-bit versions of .NET. The following example illustrates this difference when the literal value -4.42330604244772E-305 and a variable whose value is -4.42330604244772E-305 are assigned to a variable. Note that the result of the method in this case does not suffer from a loss of precision. :::code language="csharp" source="./snippets/System/Double/Overview/csharp/precision1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/precision1.fs" id="Snippet1"::: @@ -77,34 +77,34 @@ In addition, the result of arithmetic and assignment operations with values must represent identical values. However, because of differences in precision between values, or because of a loss of precision by one or both values, floating-point values that are expected to be identical often turn out to be unequal because of differences in their least significant digits. As a result, calls to the method to determine whether two values are equal, or calls to the method to determine the relationship between two values, often yield unexpected results. This is evident in the following example, where two apparently equal values turn out to be unequal because the first has 15 digits of precision, while the second has 17. +To be considered equal, two values must represent identical values. However, because of differences in precision between values, or because of a loss of precision by one or both values, floating-point values that are expected to be identical often turn out to be unequal because of differences in their least significant digits. As a result, calls to the method to determine whether two values are equal, or calls to the method to determine the relationship between two values, often yield unexpected results. This is evident in the following example, where two apparently equal values turn out to be unequal because the first has 15 digits of precision, while the second has 17. :::code language="csharp" source="./snippets/System/Double/Overview/csharp/comparison1.cs" id="Snippet9"::: :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/comparison1.fs" id="Snippet9"::: :::code language="vb" source="./snippets/System/Double/Overview/vb/comparison1.vb" id="Snippet9"::: -Calculated values that follow different code paths and that are manipulated in different ways often prove to be unequal. In the following example, one value is squared, and then the square root is calculated to restore the original value. A second is multiplied by 3.51 and squared before the square root of the result is divided by 3.51 to restore the original value. Although the two values appear to be identical, a call to the method indicates that they are not equal. Using the "R" standard format string to return a result string that displays all the significant digits of each Double value shows that the second value is .0000000000001 less than the first. +Calculated values that follow different code paths and that are manipulated in different ways often prove to be unequal. In the following example, one value is squared, and then the square root is calculated to restore the original value. A second is multiplied by 3.51 and squared before the square root of the result is divided by 3.51 to restore the original value. Although the two values appear to be identical, a call to the method indicates that they are not equal. Using the "R" standard format string to return a result string that displays all the significant digits of each Double value shows that the second value is .0000000000001 less than the first. :::code language="csharp" source="./snippets/System/Double/Overview/csharp/comparison2.cs" id="Snippet10"::: :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/comparison2.fs" id="Snippet10"::: :::code language="vb" source="./snippets/System/Double/Overview/vb/comparison2.vb" id="Snippet10"::: -In cases where a loss of precision is likely to affect the result of a comparison, you can adopt any of the following alternatives to calling the or method: +In cases where a loss of precision is likely to affect the result of a comparison, you can adopt any of the following alternatives to calling the or method: -- Call the method to ensure that both values have the same precision. The following example modifies a previous example to use this approach so that two fractional values are equivalent. +- Call the method to ensure that both values have the same precision. The following example modifies a previous example to use this approach so that two fractional values are equivalent. :::code language="csharp" source="./snippets/System/Double/Overview/csharp/comparison3.cs" id="Snippet11"::: :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/comparison3.fs" id="Snippet11"::: :::code language="vb" source="./snippets/System/Double/Overview/vb/comparison3.vb" id="Snippet11"::: - The problem of precision still applies to rounding of midpoint values. For more information, see the method. + The problem of precision still applies to rounding of midpoint values. For more information, see the method. - Test for approximate equality rather than equality. This requires that you define either an absolute amount by which the two values can differ but still be equal, or that you define a relative amount by which the smaller value can diverge from the larger value. > [!WARNING] > is sometimes used as an absolute measure of the distance between two values when testing for equality. However, measures the smallest possible value that can be added to, or subtracted from, a whose value is zero. For most positive and negative values, the value of is too small to be detected. Therefore, except for values that are zero, we do not recommend its use in tests for equality. - The following example uses the latter approach to define an `IsApproximatelyEqual` method that tests the relative difference between two values. It also contrasts the result of calls to the `IsApproximatelyEqual` method and the method. + The following example uses the latter approach to define an `IsApproximatelyEqual` method that tests the relative difference between two values. It also contrasts the result of calls to the `IsApproximatelyEqual` method and the method. :::code language="csharp" source="./snippets/System/Double/Overview/csharp/comparison4.cs" id="Snippet12"::: :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/comparison4.fs" id="Snippet12"::: @@ -132,7 +132,7 @@ Unlike operations with integral types, which throw exceptions in cases of overfl - Division by zero with a dividend of zero. Note that other cases of division by zero result in either or . - - Any floating-point operation with an invalid input. For example, calling the method with a negative value returns , as does calling the method with a value that is greater than one or less than negative one. + - Any floating-point operation with an invalid input. For example, calling the method with a negative value returns , as does calling the method with a value that is greater than one or less than negative one. - Any operation with an argument whose value is . @@ -174,26 +174,26 @@ For more information on the conversion of numeric types, see [Type Conversion in The structure and related types provide methods to perform operations in the following areas: -- **Comparison of values**. You can call the method to determine whether two values are equal, or the method to determine the relationship between two values. +- **Comparison of values**. You can call the method to determine whether two values are equal, or the method to determine the relationship between two values. The structure also supports a complete set of comparison operators. For example, you can test for equality or inequality, or determine whether one value is greater than or equal to another. If one of the operands is a numeric type other than a , it is converted to a before performing the comparison. > [!WARNING] > Because of differences in precision, two values that you expect to be equal may turn out to be unequal, which affects the result of the comparison. See the [Test for equality](#test-for-equality) section for more information about comparing two values. - You can also call the , , , and methods to test for these special values. + You can also call the , , , and methods to test for these special values. - **Mathematical operations**. Common arithmetic operations, such as addition, subtraction, multiplication, and division, are implemented by language compilers and Common Intermediate Language (CIL) instructions, rather than by methods. If one of the operands in a mathematical operation is a numeric type other than a , it is converted to a before performing the operation. The result of the operation is also a value. - Other mathematical operations can be performed by calling `static` (`Shared` in Visual Basic) methods in the class. It includes additional methods commonly used for arithmetic (such as , , and ), geometry (such as and ), and calculus (such as ). + Other mathematical operations can be performed by calling `static` (`Shared` in Visual Basic) methods in the class. It includes additional methods commonly used for arithmetic (such as , , and ), geometry (such as and ), and calculus (such as ). - You can also manipulate the individual bits in a value. The method preserves a value's bit pattern in a 64-bit integer. The method returns its bit pattern in a byte array. + You can also manipulate the individual bits in a value. The method preserves a value's bit pattern in a 64-bit integer. The method returns its bit pattern in a byte array. -- **Rounding**. Rounding is often used as a technique for reducing the impact of differences between values caused by problems of floating-point representation and precision. You can round a value by calling the method. +- **Rounding**. Rounding is often used as a technique for reducing the impact of differences between values caused by problems of floating-point representation and precision. You can round a value by calling the method. -- **Formatting**. You can convert a value to its string representation by calling the method or by using the composite formatting feature. For information about how format strings control the string representation of floating-point values, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md). +- **Formatting**. You can convert a value to its string representation by calling the method or by using the composite formatting feature. For information about how format strings control the string representation of floating-point values, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md). -- **Parsing strings**. You can convert the string representation of a floating-point value to a value by calling either the or method. If the parse operation fails, the method throws an exception, whereas the method returns `false`. +- **Parsing strings**. You can convert the string representation of a floating-point value to a value by calling either the or method. If the parse operation fails, the method throws an exception, whereas the method returns `false`. - **Type conversion**. The structure provides an explicit interface implementation for the interface, which supports conversion between any two standard .NET data types. Language compilers also support the implicit conversion of values of all other standard numeric types to values. Conversion of a value of any standard numeric type to a is a widening conversion and does not require the user of a casting operator or conversion method, diff --git a/docs/fundamentals/runtime-libraries/system-drawing-drawing2d-matrix.md b/docs/fundamentals/runtime-libraries/system-drawing-drawing2d-matrix.md index 91b45e3f7cae9..3abd355367e26 100644 --- a/docs/fundamentals/runtime-libraries/system-drawing-drawing2d-matrix.md +++ b/docs/fundamentals/runtime-libraries/system-drawing-drawing2d-matrix.md @@ -45,7 +45,7 @@ The fact that the matrix of a composite transformation can be formed by multiply > [!CAUTION] > The order of a composite transformation is important. In general, rotate, then scale, then translate is not the same as scale, then rotate, then translate. Similarly, the order of matrix multiplication is important. In general, ABC is not the same as BAC. -The class provides several methods for building a composite transformation: , , , , , and . The following example creates the matrix of a composite transformation that first rotates 30 degrees, then scales by a factor of 2 in the y direction, and then translates 5 units in the x direction: +The class provides several methods for building a composite transformation: , , , , , and . The following example creates the matrix of a composite transformation that first rotates 30 degrees, then scales by a factor of 2 in the y direction, and then translates 5 units in the x direction: :::code language="csharp" source="./snippets/System.Drawing.Drawing2D/Matrix/Overview/csharp/Class1.cs" id="Snippet11"::: :::code language="vb" source="./snippets/System.Drawing.Drawing2D/Matrix/Overview/vb/Class1.vb" id="Snippet11"::: diff --git a/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md b/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md index 6f1c543471a35..0f66555d027f6 100644 --- a/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md +++ b/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md @@ -113,7 +113,7 @@ The following code example demonstrates how you can create and use a method to p The `ExpandoObject` class implements the `IDictionary` interface. This enables enumeration of members added to the instance of the `ExpandoObject` class at runtime. This can be useful if you do not know at compile time what members an instance might have. -The following code example shows how you can cast an instance of the `ExpandoObject` class to the interface and enumerate the instance's members. +The following code example shows how you can cast an instance of the `ExpandoObject` class to the interface and enumerate the instance's members. :::code language="csharp" source="./snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs" id="Snippet5"::: :::code language="vb" source="./snippets/System.Dynamic/ExpandoObject/Overview/vb/module1.vb" id="Snippet5"::: diff --git a/docs/fundamentals/runtime-libraries/system-enum.md b/docs/fundamentals/runtime-libraries/system-enum.md index 68688263d8e8f..febd9bbaff0e2 100644 --- a/docs/fundamentals/runtime-libraries/system-enum.md +++ b/docs/fundamentals/runtime-libraries/system-enum.md @@ -50,9 +50,9 @@ You can also instantiate an enumeration value in the following ways: :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/class2.fs" id="Snippet3"::: :::code language="vb" source="./snippets/System/Enum/Overview/vb/class2.vb" id="Snippet3"::: -- By calling the or method to parse a string that contains the name of a constant in the enumeration. For more information, see the [Parse enumeration values](#parse-enumeration-values) section. +- By calling the or method to parse a string that contains the name of a constant in the enumeration. For more information, see the [Parse enumeration values](#parse-enumeration-values) section. -- By calling the method to convert an integral value to an enumeration type. For more information, see the [Perform conversions](#perform-conversions) section. +- By calling the method to convert an integral value to an enumeration type. For more information, see the [Perform conversions](#perform-conversions) section. ## Enumeration best practices @@ -80,19 +80,19 @@ You can convert between an enumeration member and its underlying type by using a :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/class2.fs" id="Snippet5"::: :::code language="vb" source="./snippets/System/Enum/Overview/vb/class2.vb" id="Snippet5"::: -The class also includes a method that converts a value of any integral type to an enumeration value. The following example uses the method to convert an to an `ArrivalStatus` value. Note that, because the returns a value of type , the use of a casting or conversion operator may still be necessary to cast the object to the enumeration type. +The class also includes a method that converts a value of any integral type to an enumeration value. The following example uses the method to convert an to an `ArrivalStatus` value. Note that, because the returns a value of type , the use of a casting or conversion operator may still be necessary to cast the object to the enumeration type. :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/class2.cs" id="Snippet6"::: :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/class2.fs" id="Snippet6"::: :::code language="vb" source="./snippets/System/Enum/Overview/vb/class2.vb" id="Snippet6"::: -When converting an integer to an enumeration value, it is possible to assign a value that is not actually a member of the enumeration. To prevent this, you can pass the integer to the method before performing the conversion. The following example uses this method to determine whether the elements in an array of integer values can be converted to `ArrivalStatus` values. +When converting an integer to an enumeration value, it is possible to assign a value that is not actually a member of the enumeration. To prevent this, you can pass the integer to the method before performing the conversion. The following example uses this method to determine whether the elements in an array of integer values can be converted to `ArrivalStatus` values. :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classconversion1.cs" id="Snippet7"::: :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classconversion1.fs" id="Snippet7"::: :::code language="vb" source="./snippets/System/Enum/Overview/vb/classconversion1.vb" id="Snippet7"::: -Although the class provides explicit interface implementations of the interface for converting from an enumeration value to an integral type, you should use the methods of the class, such as , to perform these conversions. The following example illustrates how you can use the method along with the method to convert an enumeration value to its underlying type. Note that this example does not require the underlying type of the enumeration to be known at compile time. +Although the class provides explicit interface implementations of the interface for converting from an enumeration value to an integral type, you should use the methods of the class, such as , to perform these conversions. The following example illustrates how you can use the method along with the method to convert an enumeration value to its underlying type. Note that this example does not require the underlying type of the enumeration to be known at compile time. :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classconversion2.cs" id="Snippet8"::: :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classconversion2.fs" id="Snippet8"::: @@ -100,7 +100,7 @@ Although the class provides explicit interface implementation ### Parse enumeration values -The and methods allow you to convert the string representation of an enumeration value to that value. The string representation can be either the name or the underlying value of an enumeration constant. Note that the parsing methods will successfully convert string representations of numbers that are not members of a particular enumeration if the strings can be converted to a value of the enumeration's underlying type. To prevent this, the method can be called to ensure that the result of the parsing method is a valid enumeration value. The example illustrates this approach and demonstrates calls to both the and methods. Note that the non-generic parsing method returns an object that you may have to cast (in C# and F#) or convert (in Visual Basic) to the appropriate enumeration type. +The and methods allow you to convert the string representation of an enumeration value to that value. The string representation can be either the name or the underlying value of an enumeration constant. Note that the parsing methods will successfully convert string representations of numbers that are not members of a particular enumeration if the strings can be converted to a value of the enumeration's underlying type. To prevent this, the method can be called to ensure that the result of the parsing method is a valid enumeration value. The example illustrates this approach and demonstrates calls to both the and methods. Note that the non-generic parsing method returns an object that you may have to cast (in C# and F#) or convert (in Visual Basic) to the appropriate enumeration type. :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classparse1.cs" id="Snippet9"::: :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classparse1.fs" id="Snippet9"::: @@ -108,7 +108,7 @@ The and methods allow ### Format enumeration values -You can convert enumeration values to their string representations by calling the static method, as well as the overloads of the instance method. You can use a format string to control the precise way in which an enumeration value is represented as a string. For more information, see [Enumeration Format Strings](../../standard/base-types/enumeration-format-strings.md). The following example uses each of the supported enumeration format strings ("G" or "g", "D" or "d", "X" or "x", and "F" or "f" ) to convert a member of the `ArrivalStatus` enumeration to its string representations. +You can convert enumeration values to their string representations by calling the static method, as well as the overloads of the instance method. You can use a format string to control the precise way in which an enumeration value is represented as a string. For more information, see [Enumeration Format Strings](../../standard/base-types/enumeration-format-strings.md). The following example uses each of the supported enumeration format strings ("G" or "g", "D" or "d", "X" or "x", and "F" or "f" ) to convert a member of the `ArrivalStatus` enumeration to its string representations. :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classformat1.cs" id="Snippet10"::: :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classformat1.fs" id="Snippet10"::: @@ -116,15 +116,15 @@ You can convert enumeration values to their string representations by calling th ### Iterate enumeration members -The type does not implement the or interface, which would enable you to iterate members of a collection by using a `foreach` (in C#), `for..in` (in F#), or `For Each` (in Visual Basic) construct. However, you can enumerate members in either of two ways. +The type does not implement the or interface, which would enable you to iterate members of a collection by using a `foreach` (in C#), `for..in` (in F#), or `For Each` (in Visual Basic) construct. However, you can enumerate members in either of two ways. -- You can call the method to retrieve a string array containing the names of the enumeration members. Next, for each element of the string array, you can call the method to convert the string to its equivalent enumeration value. The following example illustrates this approach. +- You can call the method to retrieve a string array containing the names of the enumeration members. Next, for each element of the string array, you can call the method to convert the string to its equivalent enumeration value. The following example illustrates this approach. :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classiterate.cs" id="Snippet11"::: :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classiterate.fs" id="Snippet11"::: :::code language="vb" source="./snippets/System/Enum/Overview/vb/classiterate.vb" id="Snippet11"::: -- You can call the method to retrieve an array that contains the underlying values in the enumeration. Next, for each element of the array, you can call the method to convert the integer to its equivalent enumeration value. The following example illustrates this approach. +- You can call the method to retrieve an array that contains the underlying values in the enumeration. Next, for each element of the array, you can call the method to convert the integer to its equivalent enumeration value. The following example illustrates this approach. :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classiterate.cs" id="Snippet12"::: :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classiterate.fs" id="Snippet12"::: @@ -156,7 +156,7 @@ The following best practices should be used when defining a bitwise enumeration - Use caution if you define a negative number as a flag enumerated constant because many flag positions might be set to 1, which might make your code confusing and encourage coding errors. -- A convenient way to test whether a flag is set in a numeric value is to call the instance method, as shown in the following example. +- A convenient way to test whether a flag is set in a numeric value is to call the instance method, as shown in the following example. :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classbitwise1.cs" id="Snippet15"::: :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classbitwise1.fs" id="Snippet15"::: diff --git a/docs/fundamentals/runtime-libraries/system-environment-getenvironmentvariable.md b/docs/fundamentals/runtime-libraries/system-environment-getenvironmentvariable.md index c5531c2fac8d2..1bc8477d3fbb9 100644 --- a/docs/fundamentals/runtime-libraries/system-environment-getenvironmentvariable.md +++ b/docs/fundamentals/runtime-libraries/system-environment-getenvironmentvariable.md @@ -7,7 +7,7 @@ ms.date: 01/24/2024 [!INCLUDE [context](includes/context.md)] -The method retrieves the value of an environment variable from the current process. +The method retrieves the value of an environment variable from the current process. Environment variable names are case-sensitive on Unix-like systems but aren't case-sensitive on Windows. @@ -18,7 +18,7 @@ Environment variable names are case-sensitive on Unix-like systems but aren't ca The method retrieves an environment variable from the environment block of the current process only. It's equivalent to calling the method with a `target` value of . -To retrieve all environment variables along with their values, call the method. +To retrieve all environment variables along with their values, call the method. ### On Windows systems @@ -44,11 +44,11 @@ On Unix-like systems, the environment block of the current process includes the ## method -To retrieve all environment variables along with their values, call the method. +To retrieve all environment variables along with their values, call the method. ### On Windows systems -On Windows, the `target` parameter specifies whether the environment variable is retrieved from the current process or from the Windows operating system registry key for the current user or local machine. All per-user and per-machine environment variables are automatically copied into the environment block of the current process, as are any other environment variables that are available to the parent process that created the .NET process. However, environment variables added only to the environment block of the current process by calling either the method or the method with a `target` value of persist only for the duration of the process. +On Windows, the `target` parameter specifies whether the environment variable is retrieved from the current process or from the Windows operating system registry key for the current user or local machine. All per-user and per-machine environment variables are automatically copied into the environment block of the current process, as are any other environment variables that are available to the parent process that created the .NET process. However, environment variables added only to the environment block of the current process by calling either the method or the method with a `target` value of persist only for the duration of the process. ### On Unix-like systems @@ -58,4 +58,4 @@ Per-process environment variables are: - Those inherited from the parent process, typically the shell used to invoke `dotnet.exe` or to launch the .NET application. -- Those defined by calling either the method or the method with a `target` value of . These environment variables persist only until the `dotnet` process or the .NET application terminates. +- Those defined by calling either the method or the method with a `target` value of . These environment variables persist only until the `dotnet` process or the .NET application terminates. diff --git a/docs/fundamentals/runtime-libraries/system-exception-message.md b/docs/fundamentals/runtime-libraries/system-exception-message.md index d51aa083b3cb2..bb4ff69c53d43 100644 --- a/docs/fundamentals/runtime-libraries/system-exception-message.md +++ b/docs/fundamentals/runtime-libraries/system-exception-message.md @@ -16,7 +16,7 @@ Error messages target the developer who is handling the exception. The text of t > [!IMPORTANT] > Do not disclose sensitive information in exception messages without checking for the appropriate permissions. -The value of the property is included in the information returned by . The property is set only when creating an . If no message was supplied to the constructor for the current instance, the system supplies a default message that is formatted using the current system culture. +The value of the property is included in the information returned by . The property is set only when creating an . If no message was supplied to the constructor for the current instance, the system supplies a default message that is formatted using the current system culture. ## Examples diff --git a/docs/fundamentals/runtime-libraries/system-exception.md b/docs/fundamentals/runtime-libraries/system-exception.md index 4294219f8bbac..3896f4ff1327a 100644 --- a/docs/fundamentals/runtime-libraries/system-exception.md +++ b/docs/fundamentals/runtime-libraries/system-exception.md @@ -17,27 +17,27 @@ The class is the base class for all exceptions. When an Runtime errors can occur for a variety of reasons. However, not all errors should be handled as exceptions in your code. Here are some categories of errors that can occur at runtime and the appropriate ways to respond to them. -- **Usage errors.** A usage error represents an error in program logic that can result in an exception. However, the error should be addressed not through exception handling but by modifying the faulty code. For example, the override of the method in the following example assumes that the `obj` argument must always be non-null. +- **Usage errors.** A usage error represents an error in program logic that can result in an exception. However, the error should be addressed not through exception handling but by modifying the faulty code. For example, the override of the method in the following example assumes that the `obj` argument must always be non-null. :::code language="csharp" source="./snippets/System/Exception/Overview/csharp/usageerrors1.cs" id="Snippet4"::: :::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/usageerrors1.fs" id="Snippet4"::: :::code language="vb" source="./snippets/System/Exception/Overview/vb/usageerrors1.vb" id="Snippet4"::: - The exception that results when `obj` is `null` can be eliminated by modifying the source code to explicitly test for null before calling the override and then re-compiling. The following example contains the corrected source code that handles a `null` argument. + The exception that results when `obj` is `null` can be eliminated by modifying the source code to explicitly test for null before calling the override and then re-compiling. The following example contains the corrected source code that handles a `null` argument. :::code language="csharp" source="./snippets/System/Exception/Overview/csharp/usageerrors2.cs" id="Snippet5"::: :::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/usageerrors2.fs" id="Snippet5"::: :::code language="vb" source="./snippets/System/Exception/Overview/vb/usageerrors2.vb" id="Snippet5"::: - Instead of using exception handling for usage errors, you can use the method to identify usage errors in debug builds, and the method to identify usage errors in both debug and release builds. For more information, see [Assertions in Managed Code](/visualstudio/debugger/assertions-in-managed-code). + Instead of using exception handling for usage errors, you can use the method to identify usage errors in debug builds, and the method to identify usage errors in both debug and release builds. For more information, see [Assertions in Managed Code](/visualstudio/debugger/assertions-in-managed-code). - **Program errors.** A program error is a runtime error that cannot necessarily be avoided by writing bug-free code. - In some cases, a program error may reflect an expected or routine error condition. In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation. For example, if the user is expected to input a date in a particular format, you can parse the date string by calling the method, which returns a value that indicates whether the parse operation succeeded, instead of using the method, which throws a exception if the date string cannot be converted to a value. Similarly, if a user tries to open a file that does not exist, you can first call the method to check whether the file exists and, if it does not, prompt the user whether they want to create it. + In some cases, a program error may reflect an expected or routine error condition. In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation. For example, if the user is expected to input a date in a particular format, you can parse the date string by calling the method, which returns a value that indicates whether the parse operation succeeded, instead of using the method, which throws a exception if the date string cannot be converted to a value. Similarly, if a user tries to open a file that does not exist, you can first call the method to check whether the file exists and, if it does not, prompt the user whether they want to create it. - In other cases, a program error reflects an unexpected error condition that can be handled in your code. For example, even if you've checked to ensure that a file exists, it may be deleted before you can open it, or it may be corrupted. In that case, trying to open the file by instantiating a object or calling the method may throw a exception. In these cases, you should use exception handling to recover from the error. + In other cases, a program error reflects an unexpected error condition that can be handled in your code. For example, even if you've checked to ensure that a file exists, it may be deleted before you can open it, or it may be corrupted. In that case, trying to open the file by instantiating a object or calling the method may throw a exception. In these cases, you should use exception handling to recover from the error. -- **System failures.** A system failure is a runtime error that cannot be handled programmatically in a meaningful way. For example, any method can throw an exception if the common language runtime is unable to allocate additional memory. Ordinarily, system failures are not handled by using exception handling. Instead, you may be able to use an event such as and call the method to log exception information and notify the user of the failure before the application terminates. +- **System failures.** A system failure is a runtime error that cannot be handled programmatically in a meaningful way. For example, any method can throw an exception if the common language runtime is unable to allocate additional memory. Ordinarily, system failures are not handled by using exception handling. Instead, you may be able to use an event such as and call the method to log exception information and notify the user of the failure before the application terminates. ## Try/catch blocks @@ -63,7 +63,7 @@ Exception types support the following features: ## Exception class properties -The class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: , , , , , , , and . +The class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: , , , , , , , and . When a causal relationship exists between two or more exceptions, the property maintains this information. The outer exception is thrown in response to this inner exception. The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately. Supplementary information about the exception can be stored as a collection of key/value pairs in the property. @@ -73,7 +73,7 @@ To provide the user with extensive information about why the exception occurred, The class uses the HRESULT `COR_E_EXCEPTION`, which has the value 0x80131500. -For a list of initial property values for an instance of the class, see the constructors. +For a list of initial property values for an instance of the class, see the constructors. ## Performance considerations @@ -89,13 +89,13 @@ In many cases, an exception handler simply wants to pass the exception on to the - An application or library that encounters a fatal exception. The exception handler can log the exception and then re-throw the exception. -The recommended way to re-throw an exception is to simply use the [throw](/dotnet/csharp/language-reference/keywords/throw) statement in C#, the [reraise](../../fsharp/language-reference/exception-handling/the-raise-function.md#reraising-an-exception) function in F#, and the [Throw](../../visual-basic/language-reference/statements/throw-statement.md) statement in Visual Basic without including an expression. This ensures that all call stack information is preserved when the exception is propagated to the caller. The following example illustrates this. A string extension method, `FindOccurrences`, wraps one or more calls to without validating its arguments beforehand. +The recommended way to re-throw an exception is to simply use the [throw](/dotnet/csharp/language-reference/keywords/throw) statement in C#, the [reraise](../../fsharp/language-reference/exception-handling/the-raise-function.md#reraising-an-exception) function in F#, and the [Throw](../../visual-basic/language-reference/statements/throw-statement.md) statement in Visual Basic without including an expression. This ensures that all call stack information is preserved when the exception is propagated to the caller. The following example illustrates this. A string extension method, `FindOccurrences`, wraps one or more calls to without validating its arguments beforehand. :::code language="csharp" source="./snippets/System/Exception/Overview/csharp/rethrow1.cs" id="Snippet6"::: :::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/rethrow1.fs" id="Snippet6"::: :::code language="vb" source="./snippets/System/Exception/Overview/vb/rethrow1.vb" id="Snippet6"::: -A caller then calls `FindOccurrences` twice. In the second call to `FindOccurrences`, the caller passes a `null` as the search string, which causes the method to throw an exception. This exception is handled by the `FindOccurrences` method and passed back to the caller. Because the throw statement is used with no expression, the output from the example shows that the call stack is preserved. +A caller then calls `FindOccurrences` twice. In the second call to `FindOccurrences`, the caller passes a `null` as the search string, which causes the method to throw an exception. This exception is handled by the `FindOccurrences` method and passed back to the caller. Because the throw statement is used with no expression, the output from the example shows that the call stack is preserved. :::code language="csharp" source="./snippets/System/Exception/Overview/csharp/rethrow1.cs" id="Snippet7"::: :::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/rethrow1.fs" id="Snippet7"::: @@ -197,11 +197,11 @@ To define your own exception class: - , which uses default values to initialize the properties of a new exception object. - - , which initializes a new exception object with a specified error message. + - , which initializes a new exception object with a specified error message. - - , which initializes a new exception object with a specified error message and inner exception. + - , which initializes a new exception object with a specified error message and inner exception. - - , which is a `protected` constructor that initializes a new exception object from serialized data. You should implement this constructor if you've chosen to make your exception object serializable. + - , which is a `protected` constructor that initializes a new exception object from serialized data. You should implement this constructor if you've chosen to make your exception object serializable. The following example illustrates the use of a custom exception class. It defines a `NotPrimeException` exception that is thrown when a client tries to retrieve a sequence of prime numbers by specifying a starting number that is not prime. The exception defines a new property, `NonPrime`, that returns the non-prime number that caused the exception. Besides implementing a protected parameterless constructor and a constructor with and parameters for serialization, the `NotPrimeException` class defines three additional constructors to support the `NonPrime` property. Each constructor calls a base class constructor in addition to preserving the value of the non-prime number. The `NotPrimeException` class is also marked with the attribute. diff --git a/docs/fundamentals/runtime-libraries/system-flagsattribute.md b/docs/fundamentals/runtime-libraries/system-flagsattribute.md index bfc1eeff3c42d..7c8a7172d6f93 100644 --- a/docs/fundamentals/runtime-libraries/system-flagsattribute.md +++ b/docs/fundamentals/runtime-libraries/system-flagsattribute.md @@ -45,7 +45,7 @@ Bit fields are generally used for lists of elements that might occur in combinat ## Examples -The following example illustrates the use of the `FlagsAttribute` attribute and shows the effect on the method of using `FlagsAttribute` on an declaration. +The following example illustrates the use of the `FlagsAttribute` attribute and shows the effect on the method of using `FlagsAttribute` on an declaration. :::code language="csharp" source="./snippets/System/FlagsAttribute/Overview/csharp/flags.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/FlagsAttribute/Overview/fsharp/flags.fs" id="Snippet1"::: @@ -53,7 +53,7 @@ The following example illustrates the use of the `FlagsAttribute` attribute and The preceding example defines two color-related enumerations, `SingleHue` and `MultiHue`. The latter has the `FlagsAttribute` attribute; the former does not. The example shows the difference in behavior when a range of integers, including integers that do not represent underlying values of the enumeration type, are cast to the enumeration type and their string representations displayed. For example, note that 3 cannot be represented as a `SingleHue` value because 3 is not the underlying value of any `SingleHue` member, whereas the `FlagsAttribute` attribute makes it possible to represent 3 as a `MultiHue` value of `Black, Red`. -The following example defines another enumeration with the `FlagsAttribute` attribute and shows how to use bitwise logical and equality operators to determine whether one or more bit fields are set in an enumeration value. You can also use the method to do that, but that is not shown in this example. +The following example defines another enumeration with the `FlagsAttribute` attribute and shows how to use bitwise logical and equality operators to determine whether one or more bit fields are set in an enumeration value. You can also use the method to do that, but that is not shown in this example. :::code language="csharp" source="./snippets/System/FlagsAttribute/Overview/csharp/flags1.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/FlagsAttribute/Overview/fsharp/flags1.fs" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-gc.md b/docs/fundamentals/runtime-libraries/system-gc.md index 067c2069db414..e167d63afdf30 100644 --- a/docs/fundamentals/runtime-libraries/system-gc.md +++ b/docs/fundamentals/runtime-libraries/system-gc.md @@ -9,7 +9,7 @@ ms.date: 12/31/2023 The class controls the garbage collector. The garbage collector is a common language runtime component that controls the allocation and release of managed memory. The methods in this class influence when garbage collection is performed on an object and when resources allocated by an object are released. Properties in this class provide information about the total amount of memory available in the system and the age category, or generation, of memory allocated to an object. -The garbage collector tracks and reclaims objects allocated in managed memory. Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. Alternatively, an application can force garbage collection using the method. +The garbage collector tracks and reclaims objects allocated in managed memory. Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. Alternatively, an application can force garbage collection using the method. Garbage collection consists of the following steps: @@ -19,13 +19,13 @@ Garbage collection consists of the following steps: ## Unmanaged resources -During a collection, the garbage collector will not free an object if it finds one or more references to the object in managed code. However, the garbage collector does not recognize references to an object from unmanaged code, and might free objects that are being used exclusively in unmanaged code unless explicitly prevented from doing so. The method provides a mechanism that prevents the garbage collector from collecting objects that are still in use in unmanaged code. +During a collection, the garbage collector will not free an object if it finds one or more references to the object in managed code. However, the garbage collector does not recognize references to an object from unmanaged code, and might free objects that are being used exclusively in unmanaged code unless explicitly prevented from doing so. The method provides a mechanism that prevents the garbage collector from collecting objects that are still in use in unmanaged code. Aside from managed memory allocations, implementations of the garbage collector do not maintain information about resources held by an object, such as file handles or database connections. When a type uses unmanaged resources that must be released before instances of the type are reclaimed, the type can implement a finalizer. -In most cases, finalizers are implemented by overriding the method; however, types written in C# or C++ implement destructors, which compilers turn into an override of . In most cases, if an object has a finalizer, the garbage collector calls it prior to freeing the object. However, the garbage collector is not required to call finalizers in all situations; for example, the method explicitly prevents an object's finalizer from being called. Also, the garbage collector is not required to use a specific thread to finalize objects, or guarantee the order in which finalizers are called for objects that reference each other but are otherwise available for garbage collection. +In most cases, finalizers are implemented by overriding the method; however, types written in C# or C++ implement destructors, which compilers turn into an override of . In most cases, if an object has a finalizer, the garbage collector calls it prior to freeing the object. However, the garbage collector is not required to call finalizers in all situations; for example, the method explicitly prevents an object's finalizer from being called. Also, the garbage collector is not required to use a specific thread to finalize objects, or guarantee the order in which finalizers are called for objects that reference each other but are otherwise available for garbage collection. -In scenarios where resources must be released at a specific time, classes can implement the interface, which contains the method that performs resource management and cleanup tasks. Classes that implement must specify, as part of their class contract, if and when class consumers call the method to clean up the object. The garbage collector does not, by default, call the method; however, implementations of the method can call methods in the class to customize the finalization behavior of the garbage collector. +In scenarios where resources must be released at a specific time, classes can implement the interface, which contains the method that performs resource management and cleanup tasks. Classes that implement must specify, as part of their class contract, if and when class consumers call the method to clean up the object. The garbage collector does not, by default, call the method; however, implementations of the method can call methods in the class to customize the finalization behavior of the garbage collector. For more information on object finalization and the dispose pattern, see [Cleaning Up Unmanaged Resources](../../standard/garbage-collection/unmanaged.md). @@ -33,12 +33,12 @@ For more information on object finalization and the dispose pattern, see [Cleani The garbage collector in the common language runtime supports object aging using generations. A generation is a unit of measure of the relative age of objects in memory. The generation number, or age, of an object indicates the generation to which an object belongs. Objects created more recently are part of newer generations, and have lower generation numbers than objects created earlier in the application life cycle. Objects in the most recent generation are in generation 0. This implementation of the garbage collector supports three generations of objects, generations 0, 1, and 2. You can retrieve the value of the property to determine the maximum generation number supported by the system. -Object aging allows applications to target garbage collection at a specific set of generations rather than requiring the garbage collector to evaluate all generations. Overloads of the method that include a `generation` parameter allow you to specify the oldest generation to be garbage collected. +Object aging allows applications to target garbage collection at a specific set of generations rather than requiring the garbage collector to evaluate all generations. Overloads of the method that include a `generation` parameter allow you to specify the oldest generation to be garbage collected. ## Disallowing garbage collection The garbage collector supports a no GC region latency mode that can be used during the execution of critical paths in which garbage collection can adversely affect an app's performance. The no GC region latency mode requires that you specify an amount of memory that can be allocated without interference from the garbage collector. If the runtime can allocate that memory, the runtime will not perform a garbage collection while code in the critical path is executing. -You define the beginning of the critical path of the no GC region by calling one of the overloads of the . You specify the end of its critical path by calling the method. +You define the beginning of the critical path of the no GC region by calling one of the overloads of the . You specify the end of its critical path by calling the method. -You cannot nest calls to the method, and you should only call the method if the runtime is currently in no GC region latency mode. In other words, you should not call multiple times (after the first method call, subsequent calls will not succeed), and you should not expect calls to to succeed just because the first call to succeeded. +You cannot nest calls to the method, and you should only call the method if the runtime is currently in no GC region latency mode. In other words, you should not call multiple times (after the first method call, subsequent calls will not succeed), and you should not expect calls to to succeed just because the first call to succeeded. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md index 83808127df575..ae2b68cfd9812 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md @@ -10,15 +10,15 @@ ms.topic: concept-article Conventions for comparing and sorting data vary from culture to culture. For example, sort order may be based on phonetics or on the visual representation of characters. In East Asian languages, characters are sorted by the stroke and radical of ideographs. Sorting also depends on the order languages and cultures use for the alphabet. For example, the Danish language has an "Æ" character that it sorts after "Z" in the alphabet. In addition, comparisons may be case-sensitive or case-insensitive, and casing rules may also differ by culture. The class is responsible for maintaining this culture-sensitive string comparison data and for performing culture-sensitive string operations. -Typically, you do not have to instantiate a object directly, because one is used implicitly by all non-ordinal string comparison operations, including calls to the method. However, if you do want to retrieve a object, you can do it in one of these ways: +Typically, you do not have to instantiate a object directly, because one is used implicitly by all non-ordinal string comparison operations, including calls to the method. However, if you do want to retrieve a object, you can do it in one of these ways: -- By retrieving the value of the property for a particular culture. +- By retrieving the value of the property for a particular culture. -- By calling the static method with a culture name. This allows for late-bound access to a object. +- By calling the static method with a culture name. This allows for late-bound access to a object. ## Ignored search values -Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. Comparison methods such as and do not consider such characters when they perform a culture-sensitive comparison. Ignorable characters include: +Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. Comparison methods such as and do not consider such characters when they perform a culture-sensitive comparison. Ignorable characters include: - . Culture-sensitive comparison methods will always find an empty string at the beginning (index zero) of the string being searched. @@ -28,7 +28,7 @@ Character sets include ignorable characters, which are characters that are not c ## Security considerations -If a security decision depends on a string comparison or a case change, you should use the property to ensure that the behavior is consistent, regardless of the culture settings of the operating system. +If a security decision depends on a string comparison or a case change, you should use the property to ensure that the behavior is consistent, regardless of the culture settings of the operating system. > [!NOTE] > When possible, you should use string comparison methods that have a parameter of type to specify the kind of comparison expected. As a general rule, use linguistic options (using the current culture) for comparing strings displayed in the user interface and specify or for security comparisons. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-compareoptions.md b/docs/fundamentals/runtime-libraries/system-globalization-compareoptions.md index d970a688afb51..48deba273484c 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-compareoptions.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-compareoptions.md @@ -12,7 +12,7 @@ The options denote case sensitivity o .NET uses three distinct ways of sorting: word sort, string sort, and ordinal sort. Word sort performs a culture-sensitive comparison of strings. Certain nonalphanumeric characters might have special weights assigned to them. For example, the hyphen ("-") might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. String sort is similar to word sort, except that there are no special cases. Therefore, all nonalphanumeric symbols come before all alphanumeric characters. Ordinal sort compares strings based on the Unicode values of each element of the string. For a downloadable set of text files that contain information on the character weights used in sorting and comparison operations for Windows operating systems, see [Sorting Weight Tables](https://www.microsoft.com/download/details.aspx?id=10921). For the sort weight table for Linux and macOS, see the [Default Unicode Collation Element Table](https://www.unicode.org/Public/UCA/latest/allkeys.txt). The specific version of the sort weight table on Linux and macOS depends on the version of the [International Components for Unicode](https://icu.unicode.org/) libraries installed on the system. For information on ICU versions and the Unicode versions that they implement, see [Downloading ICU](https://icu.unicode.org/download). -The `StringSort` value can only be used with and . is thrown if the StringSort value is used with , , , or . +The `StringSort` value can only be used with and . is thrown if the StringSort value is used with , , , or . > [!NOTE] > When possible, you should use string comparison methods that accept a value to specify the kind of comparison expected. As a general rule, user-facing comparisons are best served by the use of linguistic options (using the current culture), while security comparisons should specify `Ordinal` or `OrdinalIgnoreCase`. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder-ctor.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder-ctor.md index 2f1487a2293fb..93ff83bca9bc9 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder-ctor.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder-ctor.md @@ -13,9 +13,9 @@ The `cultureName` parameter specifies the name of the new value that specifies whether the new object is a new custom culture, or replaces an existing neutral culture, specific culture, or Windows locale. -If the `cultureName` parameter specifies an existing .NET culture, registered custom culture, or culture generated from a Windows locale, the constructor automatically populates the new object with culture and country/region information. +If the `cultureName` parameter specifies an existing .NET culture, registered custom culture, or culture generated from a Windows locale, the constructor automatically populates the new object with culture and country/region information. -Populate the new object with culture and country/region information by invoking the and methods. +Populate the new object with culture and country/region information by invoking the and methods. ## Custom culture names diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder.md index af7a426bc7746..a2e037fe12081 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder.md @@ -20,32 +20,32 @@ By default, .NET supports objects that r A custom culture can be registered on a computer only by a user who has administrative rights on that computer. Consequently, apps typically do not create and install custom cultures. Instead, you can use the class to create a special-purpose tool that an administrator can use to create, install, and register a custom culture. After the custom culture is registered on a computer, you can use the class in your app to create instances of the custom culture just as you would for a predefined culture. -If you parse date and time strings generated for a custom culture, you should use the or method instead of the or method to improve the probability that the parse operation will succeed. A date and time string for a custom culture can be complicated and therefore difficult to parse. The and methods try to parse a string with several implicit parse patterns, all of which might fail. The method, in contrast, requires the application to explicitly designate one or more exact parse patterns that are likely to succeed. +If you parse date and time strings generated for a custom culture, you should use the or method instead of the or method to improve the probability that the parse operation will succeed. A date and time string for a custom culture can be complicated and therefore difficult to parse. The and methods try to parse a string with several implicit parse patterns, all of which might fail. The method, in contrast, requires the application to explicitly designate one or more exact parse patterns that are likely to succeed. ## Define and create a custom culture You use the class to define and name a custom culture. The custom culture can be an entirely new culture, a new culture that is based on an existing culture (that is, a supplemental culture), or a culture that replaces an existing .NET culture. In each case, the basic steps are the same: -1. Instantiate a object by calling its constructor. To replace an existing culture, pass that culture's name and the enumeration value to the constructor. To create a new culture or a supplemental culture, pass a unique culture name and either the or enumeration value. +1. Instantiate a object by calling its constructor. To replace an existing culture, pass that culture's name and the enumeration value to the constructor. To create a new culture or a supplemental culture, pass a unique culture name and either the or enumeration value. > [!NOTE] > If you use the enumeration value to instantiate a object, the object's properties are automatically populated with values from the object to be replaced. 2. If you're creating a new or supplemental culture: - - Populate the object's properties by calling the method and passing a object whose property values are similar to your new object. - - Populate the object's regional properties by calling the method and passing a object that represents the region of your custom culture. + - Populate the object's properties by calling the method and passing a object whose property values are similar to your new object. + - Populate the object's regional properties by calling the method and passing a object that represents the region of your custom culture. 3. Modify the properties of the object as necessary. -4. If you are planning to register the custom culture in a separate routine, call the method. This generates an XML file that you can load and register in a separate custom culture installation routine. +4. If you are planning to register the custom culture in a separate routine, call the method. This generates an XML file that you can load and register in a separate custom culture installation routine. ## Register a custom culture -If you are developing a registration application for a custom culture that is separate from the application that creates the culture, you call the method to load the XML file that contains the custom culture's definition and instantiate the object. To handle the registration, call the method. For the registration to succeed, the application that registers the custom culture must be running with administrative privileges on the target system; otherwise, the call to throws an exception. +If you are developing a registration application for a custom culture that is separate from the application that creates the culture, you call the method to load the XML file that contains the custom culture's definition and instantiate the object. To handle the registration, call the method. For the registration to succeed, the application that registers the custom culture must be running with administrative privileges on the target system; otherwise, the call to throws an exception. > [!WARNING] -> Culture data can differ between systems. If you're using the class to create a custom culture that is uniform across multiple systems and you are creating your custom culture by loading data from existing and objects and customizing it, you should develop two different utilities. The first creates the custom culture and saves it to an XML file. The second uses the method to load the custom culture from an XML file and register it on the target computer. +> Culture data can differ between systems. If you're using the class to create a custom culture that is uniform across multiple systems and you are creating your custom culture by loading data from existing and objects and customizing it, you should develop two different utilities. The first creates the custom culture and saves it to an XML file. The second uses the method to load the custom culture from an XML file and register it on the target computer. The registration process performs the following tasks: @@ -59,8 +59,8 @@ When a custom culture is successfully registered, it's indistinguishable from th You can create an instance of the custom culture in one of the following ways: -- By invoking the constructor with the culture name. -- By calling the method with the culture name. -- By calling the method with the culture name. +- By invoking the constructor with the culture name. +- By calling the method with the culture name. +- By calling the method with the culture name. -In addition, the array of objects that is returned by the method includes the custom culture. +In addition, the array of objects that is returned by the method includes the custom culture. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentculture.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentculture.md index 704a3ea3fdc2c..8be3bb627ddc5 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentculture.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentculture.md @@ -37,27 +37,27 @@ For more information about how the culture of a thread is determined, see the "C ## Get the current culture -The property is a per-thread setting; that is, each thread can have its own culture. You get the culture of the current thread by retrieving the value of the property, as the following example illustrates. +The property is a per-thread setting; that is, each thread can have its own culture. You get the culture of the current thread by retrieving the value of the property, as the following example illustrates. :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/Get1.cs" id="Snippet5"::: :::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/vb/Get1.vb" id="Snippet5"::: ## Set the CurrentCulture property explicitly -To change the culture that's used by an existing thread, you set the property to the new culture. If you explicitly change a thread's culture in this way, that change persists if the thread crosses application domain boundaries. The following example changes the current thread culture to Dutch (Netherlands). It also shows that, when the current thread crosses application domain boundaries, its current culture remains changed. +To change the culture that's used by an existing thread, you set the property to the new culture. If you explicitly change a thread's culture in this way, that change persists if the thread crosses application domain boundaries. The following example changes the current thread culture to Dutch (Netherlands). It also shows that, when the current thread crosses application domain boundaries, its current culture remains changed. :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/changeculture11.cs" id="Snippet11"::: :::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/vb/changeculture11.vb" id="Snippet11"::: > [!NOTE] -> Changing the culture by using the property requires a permission with the value set. Manipulating threads is dangerous because of the security state associated with threads. Therefore, this permission should be given only to trustworthy code, and then only as necessary. You cannot change thread culture in semi-trusted code. +> Changing the culture by using the property requires a permission with the value set. Manipulating threads is dangerous because of the security state associated with threads. Therefore, this permission should be given only to trustworthy code, and then only as necessary. You cannot change thread culture in semi-trusted code. -Starting with .NET Framework 4, you can explicitly change the current thread culture to either a specific culture (such as French (Canada)) or a neutral culture (such as French). When a object represents a neutral culture, the values of properties such as , , , , and reflect the specific culture that is associated with the neutral culture. For example, the dominant culture for the English neutral culture is English (United States); the dominant culture for the German culture is German (Germany). The following example illustrates the difference in formatting when the current culture is set to a specific culture, French (Canada), and a neutral culture, French. +Starting with .NET Framework 4, you can explicitly change the current thread culture to either a specific culture (such as French (Canada)) or a neutral culture (such as French). When a object represents a neutral culture, the values of properties such as , , , , and reflect the specific culture that is associated with the neutral culture. For example, the dominant culture for the English neutral culture is English (United States); the dominant culture for the German culture is German (Germany). The following example illustrates the difference in formatting when the current culture is set to a specific culture, French (Canada), and a neutral culture, French. :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/specific12.cs" id="Snippet12"::: :::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/vb/specific12.vb" id="Snippet12"::: -You can also use the property along with the property to set the property of an ASP.NET application to the user's preferred culture, as the following example illustrates. +You can also use the property along with the property to set the property of an ASP.NET application to the user's preferred culture, as the following example illustrates. :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/aspculture13.cs" id="Snippet13"::: :::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/vb/aspculture13.vb" id="Snippet13"::: @@ -70,7 +70,7 @@ Windows allows users to override the standard property values of the property corresponds to the current Windows system culture. -- If the current thread culture is set explicitly to a culture returned by the method, and that culture corresponds to the current Windows system culture. +- If the current thread culture is set explicitly to a culture returned by the method, and that culture corresponds to the current Windows system culture. - If the current thread culture is set explicitly to a culture instantiated by the constructor, and that culture corresponds to the current Windows system culture. @@ -78,10 +78,10 @@ In some cases, particularly for server applications, setting the current culture - By calling the constructor with a value of `false` for the `useUserOverride` argument. -- By calling the method, which returns a cached, read-only object. +- By calling the method, which returns a cached, read-only object. ## The current culture and UWP apps -In Universal Windows Platform (UWP) apps, the property is read-write, just as it is in .NET Framework and .NET Core apps; you can use it both to get and to set the current culture. However, UWP apps do not distinguish between the current culture and the current UI culture. The and properties map to the first value in the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection. +In Universal Windows Platform (UWP) apps, the property is read-write, just as it is in .NET Framework and .NET Core apps; you can use it both to get and to set the current culture. However, UWP apps do not distinguish between the current culture and the current UI culture. The and properties map to the first value in the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection. In .NET Framework and .NET Core apps, the current culture is a per-thread setting, and the property reflects the culture of the current thread only. In UWP apps, the current culture maps to the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) property, which is a global setting. Setting the property changes the culture of the entire app; culture cannot be set on a per-thread basis. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentuiculture.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentuiculture.md index 349cc2d5e9f77..93af23a680dd5 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentuiculture.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentuiculture.md @@ -23,28 +23,28 @@ The property is a per-t - By calling the Windows `GetUserDefaultUILanguage` function. -To change the user interface culture used by a thread, set the property to the new culture. If you explicitly change a thread's UI culture in this way, that change persists if the thread crosses application domain boundaries. +To change the user interface culture used by a thread, set the property to the new culture. If you explicitly change a thread's UI culture in this way, that change persists if the thread crosses application domain boundaries. > [!NOTE] > If you set the property value to a object that represents a new culture, the value of the `Thread.CurrentThread.CurrentCulture` property also changes. ## Get the current UI culture -The property is a per-thread setting; that is, each thread can have its own UI culture. You get the UI culture of the current thread by retrieving the value of the property, as the following example illustrates. +The property is a per-thread setting; that is, each thread can have its own UI culture. You get the UI culture of the current thread by retrieving the value of the property, as the following example illustrates. :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/Get1.cs" id="Snippet5"::: :::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentUICulture/vb/Get1.vb" id="Snippet5"::: -You can also retrieve the value of the current thread's UI culture from the property. +You can also retrieve the value of the current thread's UI culture from the property. ## Explicitly set the current UI culture -Starting with .NET Framework 4.6, you can change the current UI culture by assigning a object that represents the new culture to the property. The current UI culture can be set to either a specific culture (such as en-US or de-DE) or to a neutral culture (such as en or de). The following example sets the current UI culture to fr-FR or French (France). +Starting with .NET Framework 4.6, you can change the current UI culture by assigning a object that represents the new culture to the property. The current UI culture can be set to either a specific culture (such as en-US or de-DE) or to a neutral culture (such as en or de). The following example sets the current UI culture to fr-FR or French (France). :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/currentuiculture1.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentUICulture/vb/currentuiculture1.vb" id="Snippet1"::: -In a multithreaded application, you can explicitly set the UI culture of any thread by assigning a object that represents that culture to the thread's property. If the thread whose culture you want to set is the current thread, you can assign the new culture to the property. When the UI culture of a thread is set explicitly, that thread retains the same culture even if it crosses application domain boundaries and executes code in another application domain. +In a multithreaded application, you can explicitly set the UI culture of any thread by assigning a object that represents that culture to the thread's property. If the thread whose culture you want to set is the current thread, you can assign the new culture to the property. When the UI culture of a thread is set explicitly, that thread retains the same culture even if it crosses application domain boundaries and executes code in another application domain. ## Implicitly set the current UI culture @@ -66,6 +66,6 @@ Changing the culture of the current thread requires a property is read-write, just as it is in .NET Framework and .NET Core apps; you can use it both to get and to set the current culture. However, UWP apps do not distinguish between the current culture and the current UI culture. The and properties map to the first value in the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection. +In Universal Windows Platform (UWP) apps, the property is read-write, just as it is in .NET Framework and .NET Core apps; you can use it both to get and to set the current culture. However, UWP apps do not distinguish between the current culture and the current UI culture. The and properties map to the first value in the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection. In .NET Framework and .NET Core apps, the current UI culture is a per-thread setting, and the property reflects the UI culture of the current thread only. In UWP apps, the current culture maps to the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) property, which is a global setting. Setting the property changes the culture of the entire app; culture cannot be set on a per-thread basis. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-invariantculture.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-invariantculture.md index a239224adde03..35c34ee6a62ae 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-invariantculture.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-invariantculture.md @@ -10,19 +10,19 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The invariant culture is culture-insensitive; it's associated with the English language but not with any country/region. You specify the invariant culture by name by using an empty string ("") in the call to a instantiation method. This property, , also retrieves an instance of the invariant culture. It can be used in almost any method in the namespace that requires a culture. The objects returned by properties such as , , and also reflect the string comparison and formatting conventions of the invariant culture. +The invariant culture is culture-insensitive; it's associated with the English language but not with any country/region. You specify the invariant culture by name by using an empty string ("") in the call to a instantiation method. This property, , also retrieves an instance of the invariant culture. It can be used in almost any method in the namespace that requires a culture. The objects returned by properties such as , , and also reflect the string comparison and formatting conventions of the invariant culture. Unlike culture-sensitive data, which is subject to change by user customization or by updates to the .NET Framework or the operating system, invariant culture data is stable over time and across installed cultures and cannot be customized by users. This makes the invariant culture particularly useful for operations that require culture-independent results, such as formatting and parsing operations that persist formatted data, or sorting and ordering operations that require that data be displayed in a fixed order regardless of culture. ## String operations -You can use the invariant culture for culture-sensitive string operations that are not affected by the conventions of the current culture and that are consistent across cultures. For example, you may want sorted data to appear in a fixed order or apply a standard set of casing conventions to strings regardless of the current culture. To do this, you pass the object to a method that has a parameter, such as and . +You can use the invariant culture for culture-sensitive string operations that are not affected by the conventions of the current culture and that are consistent across cultures. For example, you may want sorted data to appear in a fixed order or apply a standard set of casing conventions to strings regardless of the current culture. To do this, you pass the object to a method that has a parameter, such as and . ## Persisting data The property can be used to persist data in a culture-independent format. This provides a known format that does not change and that can be used to serialize and deserialize data across cultures. After the data is deserialized, it can be formatted appropriately based on the cultural conventions of the current user. -For example, if you choose to persist date and time data in string form, you can pass the object to the or method to create the string, and you can pass the object to the or method to convert the string back to a date and time value. This technique ensures that the underlying date and time values do not change when the data is read or written by users from different cultures. +For example, if you choose to persist date and time data in string form, you can pass the object to the or method to create the string, and you can pass the object to the or method to convert the string back to a date and time value. This technique ensures that the underlying date and time values do not change when the data is read or written by users from different cultures. The following example uses the invariant culture to persist a value as a string. It then parses the string and displays its value by using the formatting conventions of the French (France) and German (Germany) cultures. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md index 2f97b68973eb1..654a22acbde9b 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md @@ -15,7 +15,7 @@ The class provides culture-specific info The class specifies a unique name for each culture, based on RFC 4646. The name is a combination of an ISO 639 two-letter or three-letter lowercase culture code associated with a language and an ISO 3166 two-letter uppercase subculture code associated with a country or region. In addition, for apps that are running under Windows 10 or later, culture names that correspond to valid BCP-47 language tags are supported. > [!NOTE] -> When a culture name is passed to a class constructor or a method such as or , its case is not significant. +> When a culture name is passed to a class constructor or a method such as or , its case is not significant. The format for the culture name based on RFC 4646 is *`languagecode2`*-*`country/regioncode2`*, where *`languagecode2`* is the two-letter language code and *`country/regioncode2`* is the two-letter subculture code. Examples include `ja-JP` for Japanese (Japan) and `en-US` for English (United States). In cases where a two-letter language code is not available, a three-letter code as defined in ISO 639-3 is used. @@ -34,29 +34,29 @@ The culture names and identifiers represent only a subset of cultures that can b Several distinct names are closely associated with a culture, notably the names associated with the following class members: -- -- -- +- +- +- ## Invariant, neutral, and specific cultures The cultures are generally grouped into three sets: invariant cultures, neutral cultures, and specific cultures. -An invariant culture is culture-insensitive. Your application specifies the invariant culture by name using an empty string ("") or by its identifier. defines an instance of the invariant culture. It is associated with the English language but not with any country/region. It is used in almost any method in the `Globalization` namespace that requires a culture. +An invariant culture is culture-insensitive. Your application specifies the invariant culture by name using an empty string ("") or by its identifier. defines an instance of the invariant culture. It is associated with the English language but not with any country/region. It is used in almost any method in the `Globalization` namespace that requires a culture. A neutral culture is a culture that is associated with a language but not with a country/region. A specific culture is a culture that is associated with a language and a country/region. For example, `fr` is the neutral name for the French culture, and `fr-FR` is the name of the specific French (France) culture. Note that Chinese (Simplified) and Chinese (Traditional) are also considered neutral cultures. -Creating an instance of a class for a neutral culture is not recommended because the data it contains is arbitrary. To display and sort data, specify both the language and region. Additionally, the property of a object created for a neutral culture returns only the country and does not include the region. +Creating an instance of a class for a neutral culture is not recommended because the data it contains is arbitrary. To display and sort data, specify both the language and region. Additionally, the property of a object created for a neutral culture returns only the country and does not include the region. -The defined cultures have a hierarchy in which the parent of a specific culture is a neutral culture and the parent of a neutral culture is the invariant culture. The property contains the neutral culture associated with a specific culture. Custom cultures should define the property in conformance with this pattern. +The defined cultures have a hierarchy in which the parent of a specific culture is a neutral culture and the parent of a neutral culture is the invariant culture. The property contains the neutral culture associated with a specific culture. Custom cultures should define the property in conformance with this pattern. If the resources for a specific culture are not available in the operating system, the resources for the associated neutral culture are used. If the resources for the neutral culture are not available, the resources embedded in the main assembly are used. For more information on the resource fallback process, see [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps). -The list of locales in the Windows API is slightly different from the list of cultures supported by .NET. If interoperability with Windows is required, for example, through the p/invoke mechanism, the application should use a specific culture that's defined for the operating system. Use of the specific culture ensures consistency with the equivalent Windows locale, which is identified with a locale identifier that is the same as . +The list of locales in the Windows API is slightly different from the list of cultures supported by .NET. If interoperability with Windows is required, for example, through the p/invoke mechanism, the application should use a specific culture that's defined for the operating system. Use of the specific culture ensures consistency with the equivalent Windows locale, which is identified with a locale identifier that is the same as . A or a can be created only for the invariant culture or for specific cultures, not for neutral cultures. -If is the but the is not set to `zh-TW`, then , , and return an empty string (""). +If is the but the is not set to `zh-TW`, then , , and return an empty string (""). ## Custom cultures @@ -72,11 +72,11 @@ On Windows, you can create custom locales. For more information, see [Custom loc Because of this, a culture available on a particular .NET implementation, platform, or version may not be available on a different .NET implementation, platform, or version. -Some `CultureInfo` objects differ depending on the underlying platform. In particular, `zh-CN`, or Chinese (Simplified, China) and `zh-TW`, or Chinese (Traditional, Taiwan), are available cultures on Windows systems, but they are aliased cultures on Unix systems. "zh-CN" is an alias for the "zh-Hans-CN" culture, and "zh-TW" is an alias for the "zh-Hant-TW" culture. Aliased cultures are not returned by calls to the method and may have different property values, including different cultures, than their Windows counterparts. For the `zh-CN` and `zh-TW` cultures, these differences include the following: +Some `CultureInfo` objects differ depending on the underlying platform. In particular, `zh-CN`, or Chinese (Simplified, China) and `zh-TW`, or Chinese (Traditional, Taiwan), are available cultures on Windows systems, but they are aliased cultures on Unix systems. "zh-CN" is an alias for the "zh-Hans-CN" culture, and "zh-TW" is an alias for the "zh-Hant-TW" culture. Aliased cultures are not returned by calls to the method and may have different property values, including different cultures, than their Windows counterparts. For the `zh-CN` and `zh-TW` cultures, these differences include the following: - On Windows systems, the parent culture of the "zh-CN" culture is "zh-Hans", and the parent culture of the "zh-TW" culture is "zh-Hant". The parent culture of both these cultures is "zh". On Unix systems, the parents of both cultures are "zh". This means that, if you don't provide culture-specific resources for the "zh-CN" or "zh-TW" cultures but do provide a resources for the neutral "zh-Hans" or "zh-Hant" culture, your application will load the resources for the neutral culture on Windows but not on Unix. On Unix systems, you must explicitly set the thread's to either "zh-Hans" or "zh-Hant". -- On Windows systems, calling on an instance that represents the "zh-CN" culture and passing it a "zh-Hans-CN" instance returns `true`. On Unix systems, the method call returns `false`. This behavior also applies to calling on a "zh-TW" instance and passing it a "zh-Hant-Tw" instance. +- On Windows systems, calling on an instance that represents the "zh-CN" culture and passing it a "zh-Hans-CN" instance returns `true`. On Unix systems, the method call returns `false`. This behavior also applies to calling on a "zh-TW" instance and passing it a "zh-Hant-Tw" instance. ## Dynamic culture data @@ -92,13 +92,13 @@ Every thread in a .NET application has a current culture and a current UI cultur > [!NOTE] > For information on how the current and current UI culture is determined on a per-thread basis, see the [Culture and threads](#culture-and-threads) section. For information on how the current and current UI culture is determined on threads executing in a new application domain, and on threads that cross application domain boundaries, see the [Culture and application domains](#culture-and-application-domains) section. For information on how the current and current UI culture is determined on threads performing task-based asynchronous operations, see the [Culture and task-based asynchronous operations](#culture-and-task-based-asynchronous-operations) section. -For more detailed information on the current culture, see the property. For more detailed information on the current UI culture, see the property topic. +For more detailed information on the current culture, see the property. For more detailed information on the current UI culture, see the property topic. ### Retrieve the current and current UI cultures You can get a object that represents the current culture in either of two ways: -- By retrieving the value of the property. +- By retrieving the value of the property. - By retrieving the value of the [Thread.CurrentThread.CurrentCulture]() property. The following example retrieves both property values, compares them to show that they are equal, and displays the name of the current culture. @@ -107,7 +107,7 @@ The following example retrieves both property values, compares them to show that You can get a object that represents the current UI culture in either of two ways: -- By retrieving the value of the property. +- By retrieving the value of the property. - By retrieving the value of the [Thread.CurrentThread.CurrentUICulture]() property. @@ -119,9 +119,9 @@ The following example retrieves both property values, compares them to show that To change the culture and UI culture of a thread, do the following: -1. Instantiate a object that represents that culture by calling a class constructor and passing it the name of the culture. The constructor instantiates a object that reflects user overrides if the new culture is the same as the current Windows culture. The constructor allows you to specify whether the newly instantiated object reflects user overrides if the new culture is the same as the current Windows culture. +1. Instantiate a object that represents that culture by calling a class constructor and passing it the name of the culture. The constructor instantiates a object that reflects user overrides if the new culture is the same as the current Windows culture. The constructor allows you to specify whether the newly instantiated object reflects user overrides if the new culture is the same as the current Windows culture. -2. Assign the object to the or property on .NET Core and .NET Framework 4.6 and later versions. +2. Assign the object to the or property on .NET Core and .NET Framework 4.6 and later versions. The following example retrieves the current culture. If it is anything other than the French (France) culture, it changes the current culture to French (France). Otherwise, it changes the current culture to French (Luxembourg). @@ -133,9 +133,9 @@ The following example retrieves the current culture. If it is anything other the ## Get all cultures -You can retrieve an array of specific categories of cultures or of all the cultures available on the local computer by calling the method. For example, you can retrieve custom cultures, specific cultures, or neutral cultures either alone or in combination. +You can retrieve an array of specific categories of cultures or of all the cultures available on the local computer by calling the method. For example, you can retrieve custom cultures, specific cultures, or neutral cultures either alone or in combination. -The following example calls the method twice, first with the enumeration member to retrieve all custom cultures, and then with the enumeration member to retrieve all replacement cultures. +The following example calls the method twice, first with the enumeration member to retrieve all custom cultures, and then with the enumeration member to retrieve all replacement cultures. :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/GetCultures1.cs" id="Snippet5"::: @@ -145,18 +145,18 @@ When a new application thread is started, its current culture and current UI cul :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/defaultthread1.cs" id="Snippet1"::: -You can set the culture and UI culture of all threads in an application domain by assigning a object that represents that culture to the and properties. The following example uses these properties to ensure that all threads in the default application domain share the same culture. +You can set the culture and UI culture of all threads in an application domain by assigning a object that represents that culture to the and properties. The following example uses these properties to ensure that all threads in the default application domain share the same culture. :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/setthreads1.cs" id="Snippet3"::: > [!WARNING] -> Although the and properties are static members, they define the default culture and default UI culture only for the application domain that is current at the time these property values are set. For more information, see the next section, [Culture and application domains](#culture-and-application-domains). +> Although the and properties are static members, they define the default culture and default UI culture only for the application domain that is current at the time these property values are set. For more information, see the next section, [Culture and application domains](#culture-and-application-domains). -When you assign values to the and properties, the culture and UI culture of the threads in the application domain also change if they have not explicitly been assigned a culture. However, these threads reflect the new culture settings only while they execute in the current application domain. If these threads execute in another application domain, their culture becomes the default culture defined for that application domain. As a result, we recommend that you always set the culture of the main application thread, and not rely on the and properties to change it. +When you assign values to the and properties, the culture and UI culture of the threads in the application domain also change if they have not explicitly been assigned a culture. However, these threads reflect the new culture settings only while they execute in the current application domain. If these threads execute in another application domain, their culture becomes the default culture defined for that application domain. As a result, we recommend that you always set the culture of the main application thread, and not rely on the and properties to change it. ## Culture and application domains - and are static properties that explicitly define a default culture only for the application domain that is current when the property value is set or retrieved. The following example sets the default culture and default UI culture in the default application domain to French (France), and then uses the class and the delegate to set the default culture and UI culture in a new application domain to Russian (Russia). A single thread then executes two methods in each application domain. Note that the thread's culture and UI culture are not explicitly set; they are derived from the default culture and UI culture of the application domain in which the thread is executing. Note also that the and properties return the default values of the application domain that is current when the method call is made. + and are static properties that explicitly define a default culture only for the application domain that is current when the property value is set or retrieved. The following example sets the default culture and default UI culture in the default application domain to French (France), and then uses the class and the delegate to set the default culture and UI culture in a new application domain to Russian (Russia). A single thread then executes two methods in each application domain. Note that the thread's culture and UI culture are not explicitly set; they are derived from the default culture and UI culture of the application domain in which the thread is executing. Note also that the and properties return the default values of the application domain that is current when the method call is made. :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/appdomainex1.cs" id="Snippet1"::: @@ -164,37 +164,37 @@ For more information about cultures and application domains, see the "Applicatio ## Culture and task-based asynchronous operations -The [task-based asynchronous programming pattern](../../standard/parallel-programming/task-based-asynchronous-programming.md) uses and objects to asynchronously execute delegates on thread pool threads. The specific thread on which a particular task runs is not known in advance, but is determined only at runtime. +The [task-based asynchronous programming pattern](../../standard/parallel-programming/task-based-asynchronous-programming.md) uses and objects to asynchronously execute delegates on thread pool threads. The specific thread on which a particular task runs is not known in advance, but is determined only at runtime. -For apps that target .NET Framework 4.6 or a later version, culture is part of an asynchronous operation's context. In other words, asynchronous operations by default inherit the values of the and properties of the thread from which they are launched. If the current culture or current UI culture differs from the system culture, the current culture crosses thread boundaries and becomes the current culture of the thread pool thread that is executing an asynchronous operation. +For apps that target .NET Framework 4.6 or a later version, culture is part of an asynchronous operation's context. In other words, asynchronous operations by default inherit the values of the and properties of the thread from which they are launched. If the current culture or current UI culture differs from the system culture, the current culture crosses thread boundaries and becomes the current culture of the thread pool thread that is executing an asynchronous operation. -The following example provides a simple illustration. The example defines a delegate, `formatDelegate`, that returns some numbers formatted as currency values. The example changes the current system culture to either French (France) or, if French (France) is already the current culture, English (United States). It then: +The following example provides a simple illustration. The example defines a delegate, `formatDelegate`, that returns some numbers formatted as currency values. The example changes the current system culture to either French (France) or, if French (France) is already the current culture, English (United States). It then: - Invokes the delegate directly so that it runs synchronously on the main app thread. - Creates a task that executes the delegate asynchronously on a thread pool thread. -- Creates a task that executes the delegate synchronously on the main app thread by calling the method. +- Creates a task that executes the delegate synchronously on the main app thread by calling the method. As the output from the example shows, when the current culture is changed to French (France), the current culture of the thread from which tasks are invoked asynchronously becomes the current culture for that asynchronous operation. :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/asyncculture1.cs" id="Snippet1"::: - and are per-app domain properties; that is, they establish a default culture for all threads not explicitly assigned a culture in a specific application domain. However, for apps that target .NET Framework 4.6 or later, the culture of the calling thread remains part of an asynchronous task's context even if the task crosses app domain boundaries. + and are per-app domain properties; that is, they establish a default culture for all threads not explicitly assigned a culture in a specific application domain. However, for apps that target .NET Framework 4.6 or later, the culture of the calling thread remains part of an asynchronous task's context even if the task crosses app domain boundaries. ## CultureInfo object serialization -When a object is serialized, all that is actually stored is and . It is successfully deserialized only in an environment where that has the same meaning. The following three examples show why this is not always the case: +When a object is serialized, all that is actually stored is and . It is successfully deserialized only in an environment where that has the same meaning. The following three examples show why this is not always the case: -- If the property value is , and if that culture was first introduced in a particular version of the Windows operating system, it is not possible to deserialize it on an earlier version of Windows. For example, if a culture was introduced in Windows 10, it cannot be deserialized on Windows 8. +- If the property value is , and if that culture was first introduced in a particular version of the Windows operating system, it is not possible to deserialize it on an earlier version of Windows. For example, if a culture was introduced in Windows 10, it cannot be deserialized on Windows 8. -- If the value is , and the computer on which it is deserialized does not have this user custom culture installed, it is not possible to deserialize it. +- If the value is , and the computer on which it is deserialized does not have this user custom culture installed, it is not possible to deserialize it. -- If the value is , and the computer on which it is deserialized does not have this replacement culture, it deserializes to the same name, but not all of the same characteristics. For example, if `en-US` is a replacement culture on computer A, but not on computer B, and if a object referring to this culture is serialized on computer A and deserialized on computer B, then none of the custom characteristics of the culture are transmitted. The culture deserializes successfully, but with a different meaning. +- If the value is , and the computer on which it is deserialized does not have this replacement culture, it deserializes to the same name, but not all of the same characteristics. For example, if `en-US` is a replacement culture on computer A, but not on computer B, and if a object referring to this culture is serialized on computer A and deserialized on computer B, then none of the custom characteristics of the culture are transmitted. The culture deserializes successfully, but with a different meaning. ## Control Panel overrides The user might choose to override some of the values associated with the current culture of Windows through the regional and language options portion of Control Panel. For example, the user might choose to display the date in a different format or to use a currency other than the default for the culture. In general, your applications should honor these user overrides. -If is `true` and the specified culture matches the current culture of Windows, the uses those overrides, including user settings for the properties of the instance returned by the property, and the properties of the instance returned by the property. If the user settings are incompatible with the culture associated with the , for example, if the selected calendar is not one of the , the results of the methods and the values of the properties are undefined. +If is `true` and the specified culture matches the current culture of Windows, the uses those overrides, including user settings for the properties of the instance returned by the property, and the properties of the instance returned by the property. If the user settings are incompatible with the culture associated with the , for example, if the selected calendar is not one of the , the results of the methods and the values of the properties are undefined. ## Alternate sort orders @@ -222,6 +222,6 @@ The following table lists the cultures that support alternate sort orders and th ## The current culture and UWP apps -In Universal Windows Platform (UWP) apps, the and properties are read-write, just as they are in .NET Framework and .NET Core apps. However, UWP apps recognize a single culture. The and properties map to the first value in the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection. +In Universal Windows Platform (UWP) apps, the and properties are read-write, just as they are in .NET Framework and .NET Core apps. However, UWP apps recognize a single culture. The and properties map to the first value in the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection. -In .NET apps, the current culture is a per-thread setting, and the and properties reflect the culture and UI culture of the current thread only. In UWP apps, the current culture maps to the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection, which is a global setting. Setting the or property changes the culture of the entire app; culture cannot be set on a per-thread basis. +In .NET apps, the current culture is a per-thread setting, and the and properties reflect the culture and UI culture of the current thread only. In UWP apps, the current culture maps to the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection, which is a global setting. Setting the or property changes the culture of the entire app; culture cannot be set on a per-thread basis. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md index e63b1401a880b..7053f620ed45c 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md @@ -25,9 +25,9 @@ A object can represent the format The invariant culture represents a culture that is culture-insensitive. It is based on the English language, but not on any specific English-speaking country/region. Although the data of specific cultures can be dynamic and can change to reflect new cultural conventions or user preferences, the data of the invariant culture does not change. You can instantiate a object that represents the formatting conventions of the invariant culture in the following ways: -- By retrieving the value of the property. The returned object is read-only. -- By calling the parameterless constructor. The returned object is read/write. -- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. +- By retrieving the value of the property. The returned object is read-only. +- By calling the parameterless constructor. The returned object is read/write. +- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. The following example uses each of these methods to instantiate a object that represents the invariant culture. It then indicates whether the object is read-only. @@ -37,13 +37,13 @@ The following example uses each of these methods to instantiate a object that represents the formatting conventions of a specific culture in the following ways: -- By calling the method and retrieving the value of the returned object's property. The returned object is read-only. +- By calling the method and retrieving the value of the returned object's property. The returned object is read-only. -- By passing the static method a object that represents the culture whose object you want to retrieve. The returned object is read/write. +- By passing the static method a object that represents the culture whose object you want to retrieve. The returned object is read/write. -- By calling the static method and retrieving the value of the returned object's property. The returned object is read/write. +- By calling the static method and retrieving the value of the returned object's property. The returned object is read/write. -- By calling the class constructor and retrieving the value of the returned object's property. The returned object is read/write. +- By calling the class constructor and retrieving the value of the returned object's property. The returned object is read/write. The following example illustrates each of these ways to instantiate a object and indicates whether the resulting object is read-only. @@ -51,13 +51,13 @@ The following example illustrates each of these ways to instantiate a object that represents the formatting conventions of a neutral culture in the same ways that you create a object that represents the formatting conventions of a specific culture. In addition, you can retrieve a neutral culture's object by retrieving a neutral culture from a specific culture's property and retrieving the object returned by its property. Unless the parent culture represents the invariant culture, the returned object is read/write. The following example illustrates these ways of instantiating a object that represents a neutral culture. +A neutral culture represents a culture or language that is independent of a country/region; it is typically the parent of one or more specific cultures. For example, Fr is a neutral culture for the French language and the parent of the fr-FR culture. You can instantiate a object that represents the formatting conventions of a neutral culture in the same ways that you create a object that represents the formatting conventions of a specific culture. In addition, you can retrieve a neutral culture's object by retrieving a neutral culture from a specific culture's property and retrieving the object returned by its property. Unless the parent culture represents the invariant culture, the returned object is read/write. The following example illustrates these ways of instantiating a object that represents a neutral culture. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/create1.cs" id="Snippet2"::: However, a neutral culture lacks culture-specific formatting information, because it is independent of a specific country/region. Instead of populating the object with generic values, .NET returns a object that reflects the formatting conventions of a specific culture that is a child of the neutral culture. For example, the object for the neutral en culture reflects the formatting conventions of the en-US culture, and the object for the fr culture reflects the formatting conventions of the fr-FR culture. -You can use code like the following to determine which specific culture's formatting conventions a neutral culture represents. The example uses reflection to compare the properties of a neutral culture with the properties of a specific child culture. It considers two calendars to be equivalent if they are the same calendar type and, for Gregorian calendars, if their properties have identical values. +You can use code like the following to determine which specific culture's formatting conventions a neutral culture represents. The example uses reflection to compare the properties of a neutral culture with the properties of a specific child culture. It considers two calendars to be equivalent if they are the same calendar type and, for Gregorian calendars, if their properties have identical values. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate6.cs" id="Snippet6"::: @@ -65,11 +65,11 @@ You can use code like the following to determine which specific culture's format You can instantiate a object that represents the formatting conventions of the current culture in the following ways: -- By retrieving the value of the property. The returned object is read-only. +- By retrieving the value of the property. The returned object is read-only. -- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. +- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. -- By calling the method with a object that represents the current culture. The returned object is read-only. +- By calling the method with a object that represents the current culture. The returned object is read-only. The following example uses each of these methods to instantiate a object that represents the formatting conventions of the current culture. It then indicates whether the object is read-only. @@ -77,15 +77,15 @@ The following example uses each of these methods to instantiate a object that represents the conventions of the current culture in one of these ways: -- By retrieving a object in any of the three previous ways and calling the method on the returned object. This creates a copy of the original object, except that its property is `false`. +- By retrieving a object in any of the three previous ways and calling the method on the returned object. This creates a copy of the original object, except that its property is `false`. -- By calling the method to create a object that represents the current culture, and then using its property to retrieve the object. +- By calling the method to create a object that represents the current culture, and then using its property to retrieve the object. -The following example illustrates each way of instantiating a read/write object and displays the value of its property. +The following example illustrates each way of instantiating a read/write object and displays the value of its property. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate2.cs" id="Snippet7"::: -In Windows, the user can override some of the property values used in formatting and parsing operations through the **Region and Language** application in Control Panel. For example, a user whose culture is English (United States) might choose to display long time values using a 24-hour clock (in the format HH:mm:ss) instead of the default 12-hour clock (in the format h:mm:ss tt). The objects retrieved in the ways discussed previously all reflect these user overrides. If this is undesirable, you can create a object that does not reflect user overrides (and is also read/write instead of read-only) by calling the constructor and supplying a value of `false` for the `useUserOverride` argument. The following example illustrates this for a system whose current culture is English (United States) and whose long time pattern has been changed from the default of h:mm:ss tt to HH:mm:ss. +In Windows, the user can override some of the property values used in formatting and parsing operations through the **Region and Language** application in Control Panel. For example, a user whose culture is English (United States) might choose to display long time values using a 24-hour clock (in the format HH:mm:ss) instead of the default 12-hour clock (in the format h:mm:ss tt). The objects retrieved in the ways discussed previously all reflect these user overrides. If this is undesirable, you can create a object that does not reflect user overrides (and is also read/write instead of read-only) by calling the constructor and supplying a value of `false` for the `useUserOverride` argument. The following example illustrates this for a system whose current culture is English (United States) and whose long time pattern has been changed from the default of h:mm:ss tt to HH:mm:ss. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate3.cs" id="Snippet8"::: @@ -97,9 +97,9 @@ The culture-specific data for formatting date and time values provided by the class can be used to replace the data of an existing culture. -- Cascading changes to property values. A number of culture-related properties can change at runtime, which, in turn, causes data to change. For example, the current culture can be changed either programmatically or through user action. When this happens, the object returned by the property changes to an object associated with the current culture. Similarly, a culture's calendar can change, which can result in changes to numerous property values. +- Cascading changes to property values. A number of culture-related properties can change at runtime, which, in turn, causes data to change. For example, the current culture can be changed either programmatically or through user action. When this happens, the object returned by the property changes to an object associated with the current culture. Similarly, a culture's calendar can change, which can result in changes to numerous property values. -- User preferences. Users of your application might choose to override some of the values associated with the current system culture through the regional and language options in Control Panel. For example, users might choose to display the date in a different format. If the property is set to `true`, the properties of the object is also retrieved from the user settings. If the user settings are incompatible with the culture associated with the object (for example, if the selected calendar is not one of the calendars indicated by the property), the results of the methods and the values of the properties are undefined. +- User preferences. Users of your application might choose to override some of the values associated with the current system culture through the regional and language options in Control Panel. For example, users might choose to display the date in a different format. If the property is set to `true`, the properties of the object is also retrieved from the user settings. If the user settings are incompatible with the culture associated with the object (for example, if the selected calendar is not one of the calendars indicated by the property), the results of the methods and the values of the properties are undefined. To minimize the possibility of inconsistent data, all user-overridable properties of a object are initialized when the object is created. There is still a possibility of inconsistency, because neither object creation nor the user override process is atomic and the relevant values can change during object creation. However, this situation should be extremely rare. @@ -108,11 +108,11 @@ You can control whether user overrides are reflected in property|Yes| -| method|Yes| -| method|No| -| constructor|Yes| -| constructor|Depends on value of `useUserOverride` parameter| +| property|Yes| +| method|Yes| +| method|No| +| constructor|Yes| +| constructor|Depends on value of `useUserOverride` parameter| Unless there is a compelling reason to do otherwise, you should respect user overrides when you use the object in client applications to format and parse user input or to display data. For server applications or unattended applications, you should not. However, if you are using the object either explicitly or implicitly to persist date and time data in string form, you should either use a object that reflects the formatting conventions of the invariant culture, or you should specify a custom date and time format string that you use regardless of culture. @@ -120,18 +120,18 @@ Unless there is a compelling reason to do otherwise, you should respect user ove A object is used implicitly or explicitly in all date and time formatting operations. These include calls to the following methods: -- All date and time formatting methods, such as and . -- The major composite formatting method, which is . -- Other composite formatting methods, such as and . +- All date and time formatting methods, such as and . +- The major composite formatting method, which is . +- Other composite formatting methods, such as and . -All date and time formatting operations make use of an implementation. The interface includes a single method, . This callback method is passed a object that represents the type needed to provide formatting information. The method returns either an instance of that type or `null` if it cannot provide an instance of the type. .NET includes two implementations for formatting dates and times: +All date and time formatting operations make use of an implementation. The interface includes a single method, . This callback method is passed a object that represents the type needed to provide formatting information. The method returns either an instance of that type or `null` if it cannot provide an instance of the type. .NET includes two implementations for formatting dates and times: -- The class, which represents a specific culture (or a specific language in a specific country/region). In a date and time formatting operation, the method returns the object associated with its property. -- The class, which provides information about the formatting conventions of its associated culture. The method returns an instance of itself. +- The class, which represents a specific culture (or a specific language in a specific country/region). In a date and time formatting operation, the method returns the object associated with its property. +- The class, which provides information about the formatting conventions of its associated culture. The method returns an instance of itself. -If an implementation is not provided to a formatting method explicitly, the object returned by the property that represents the current culture is used. +If an implementation is not provided to a formatting method explicitly, the object returned by the property that represents the current culture is used. -The following example illustrates the relationship between the interface and the class in formatting operations. It defines a custom implementation whose method displays the type of the object requested by the formatting operation. If it is requesting a object, the method provides the object for the current culture. As the output from the example shows, the method requests a object to provide formatting information, whereas the method requests and objects as well as an implementation. +The following example illustrates the relationship between the interface and the class in formatting operations. It defines a custom implementation whose method displays the type of the object requested by the formatting operation. If it is requesting a object, the method provides the object for the current culture. As the output from the example shows, the method requests a object to provide formatting information, whereas the method requests and objects as well as an implementation. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/formatprovider1.cs" id="Snippet9"::: @@ -139,43 +139,43 @@ The following example illustrates the relationship between the object includes three kinds of properties that are used in formatting operations with date and time values: -- Calendar-related properties. Properties such as , , , and , are associated with the calendar used by the culture, which is defined by the property. These properties are used for long date and time formats. +- Calendar-related properties. Properties such as , , , and , are associated with the calendar used by the culture, which is defined by the property. These properties are used for long date and time formats. -- Properties that produce a standards-defined result string. The , , and properties contain custom format strings that produce result strings defined by international standards. These properties are read-only and cannot be modified. +- Properties that produce a standards-defined result string. The , , and properties contain custom format strings that produce result strings defined by international standards. These properties are read-only and cannot be modified. -- Properties that define culture-sensitive result strings. Some properties, such as and , contain [custom format strings](../../standard/base-types/custom-date-and-time-format-strings.md) that specify the format of the result string. Others, such as , , , and , define culture-sensitive symbols or substrings that can be included in a result string. +- Properties that define culture-sensitive result strings. Some properties, such as and , contain [custom format strings](../../standard/base-types/custom-date-and-time-format-strings.md) that specify the format of the result string. Others, such as , , , and , define culture-sensitive symbols or substrings that can be included in a result string. The [standard date and time format strings](../../standard/base-types/standard-date-and-time-format-strings.md), such as "d", "D", "f", and "F", are aliases that correspond to particular format pattern properties. Most of the [custom date and time format strings](../../standard/base-types/custom-date-and-time-format-strings.md) are related to strings or substrings that a formatting operation inserts into the result stream. The following table lists the standard and custom date and time format specifiers and their associated properties. For details about how to use these format specifiers, see [Standard Date and Time Format Strings](../../standard/base-types/standard-date-and-time-format-strings.md) and [Custom Date and Time Format Strings](../../standard/base-types/custom-date-and-time-format-strings.md). Note that each standard format string corresponds to a property whose value is a custom date and time format string. The individual specifiers in this custom format string in turn correspond to other properties. The table lists only the properties for which the standard format strings are aliases, and does not list properties that may be accessed by custom format strings assigned to those aliased properties. In addition, the table lists only custom format specifiers that correspond to properties. |Format specifier|Associated properties| |----------------------|---------------------------| -|"d" (short date; standard format string)|, to define the overall format of the result string.| -|"D" (long date; standard format string)|, to define the overall format of the result string.| -|"f" (full date / short time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| -|"F" (full date / long time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| -|"g" (general date / short time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| -|"G" (general date / long time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| -|"M", "m" (month/day; standard format string)|, to define the overall format of the result string.| +|"d" (short date; standard format string)|, to define the overall format of the result string.| +|"D" (long date; standard format string)|, to define the overall format of the result string.| +|"f" (full date / short time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| +|"F" (full date / long time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| +|"g" (general date / short time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| +|"G" (general date / long time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| +|"M", "m" (month/day; standard format string)|, to define the overall format of the result string.| |"O", "o" (round-trip date/time; standard format string)|None.| -|"R", "r" (RFC1123; standard format string)|, to define a result string that conforms to the RFC 1123 standard. The property is read-only.| -|"s" (sortable date/time; standard format string)|, to define a result string that conforms to the ISO 8601 standard. The property is read-only.| -|"t" (short time; standard format string)|, to define the overall format of the result string.| -|"T" (long time; standard format string)|, to define the overall format of the result string.| -|"u" (universal sortable date/time; standard format string)|, to define a result string that conforms to the ISO 8601 standard for coordinated universal time. The property is read-only.| -|"U" (universal full date/time; standard format string)|, to define the overall format of the result string.| -|"Y", "y" (year month; standard format string)|, to define the overall format of the result string.| -|"ddd" (custom format specifier)|, to include the abbreviated name of the day of the week in the result string.| -|"g", "gg" (custom format specifier)|Calls the method to insert the era name in the result string.| -|"MMM" (custom format specifier)| or , to include the abbreviated month name in the result string.| -|"MMMM" (custom format specifier)| or , to include the full month name in the result string.| -|"t" (custom format specifier)| or , to include the first character of the AM/PM designator in the result string.| -|"tt" (custom format specifier)| or , to include the full AM/PM designator in the result string.| -|":" (custom format specifier)|, to include the time separator in the result string.| -|"/" (custom format specifier)|, to include the date separator in the result string.| +|"R", "r" (RFC1123; standard format string)|, to define a result string that conforms to the RFC 1123 standard. The property is read-only.| +|"s" (sortable date/time; standard format string)|, to define a result string that conforms to the ISO 8601 standard. The property is read-only.| +|"t" (short time; standard format string)|, to define the overall format of the result string.| +|"T" (long time; standard format string)|, to define the overall format of the result string.| +|"u" (universal sortable date/time; standard format string)|, to define a result string that conforms to the ISO 8601 standard for coordinated universal time. The property is read-only.| +|"U" (universal full date/time; standard format string)|, to define the overall format of the result string.| +|"Y", "y" (year month; standard format string)|, to define the overall format of the result string.| +|"ddd" (custom format specifier)|, to include the abbreviated name of the day of the week in the result string.| +|"g", "gg" (custom format specifier)|Calls the method to insert the era name in the result string.| +|"MMM" (custom format specifier)| or , to include the abbreviated month name in the result string.| +|"MMMM" (custom format specifier)| or , to include the full month name in the result string.| +|"t" (custom format specifier)| or , to include the first character of the AM/PM designator in the result string.| +|"tt" (custom format specifier)| or , to include the full AM/PM designator in the result string.| +|":" (custom format specifier)|, to include the time separator in the result string.| +|"/" (custom format specifier)|, to include the date separator in the result string.| ## Modify DateTimeFormatInfo properties -You can change the result string produced by date and time format strings by modifying the associated properties of a writable object. To determine if a object is writable, use the property. To customize a object in this way: +You can change the result string produced by date and time format strings by modifying the associated properties of a writable object. To determine if a object is writable, use the property. To customize a object in this way: 1. Create a read/write copy of a object whose formatting conventions you want to modify. @@ -187,27 +187,27 @@ There are two other ways to change the format of a result string: - You can use the class to define either a custom culture (a culture that has a unique name and that supplements existing cultures) or a replacement culture (one that is used instead of a specific culture). You can save and access this culture programmatically as you would any object supported by .NET. -- If the result string is not culture-sensitive and doesn't follow a predefined format, you can use a custom date and time format string. For example, if you are serializing date and time data in the format YYYYMMDDHHmmss, you can generate the result string by passing the custom format string to the method, and you can convert the result string back to a value by calling the method. +- If the result string is not culture-sensitive and doesn't follow a predefined format, you can use a custom date and time format string. For example, if you are serializing date and time data in the format YYYYMMDDHHmmss, you can generate the result string by passing the custom format string to the method, and you can convert the result string back to a value by calling the method. ### Change the short date pattern -The following example changes the format of a result string produced by the "d" (short date) standard format string. It changes the associated property for the en-US or English (United States) culture from its default of "M/d/yyyy" to "yyyy'-"MM"-"dd" and uses the "d" standard format string to display the date both before and after the property is changed. +The following example changes the format of a result string produced by the "d" (short date) standard format string. It changes the associated property for the en-US or English (United States) culture from its default of "M/d/yyyy" to "yyyy'-"MM"-"dd" and uses the "d" standard format string to display the date both before and after the property is changed. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example1.cs" id="Snippet10"::: ### Change the date separator character -The following example changes the date separator character in a object that represents the formatting conventions of the fr-FR culture. The example uses the "g" standard format string to display the date both before and after the property is changed. +The following example changes the date separator character in a object that represents the formatting conventions of the fr-FR culture. The example uses the "g" standard format string to display the date both before and after the property is changed. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example3.cs" id="Snippet12"::: ### Change day name abbreviations and the long date pattern -In some cases, the long date pattern, which typically displays the full day and month name along with the number of the day of the month and the year, may be too long. The following example shortens the long date pattern for the en-US culture to return a one-character or two-character day name abbreviation followed by the day number, the month name abbreviation, and the year. It does this by assigning shorter day name abbreviations to the array, and by modifying the custom format string assigned to the property. This affects the result strings returned by the "D" and "f" standard format strings. +In some cases, the long date pattern, which typically displays the full day and month name along with the number of the day of the month and the year, may be too long. The following example shortens the long date pattern for the en-US culture to return a one-character or two-character day name abbreviation followed by the day number, the month name abbreviation, and the year. It does this by assigning shorter day name abbreviations to the array, and by modifying the custom format string assigned to the property. This affects the result strings returned by the "D" and "f" standard format strings. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example2.cs" id="Snippet13"::: -Ordinarily, the change to the property also affects the property, which in turn defines the result string returned by the "F" standard format string. To preserve the original full date and time pattern, the example reassigns the original custom format string assigned to the property after the property is modified. +Ordinarily, the change to the property also affects the property, which in turn defines the result string returned by the "F" standard format string. To preserve the original full date and time pattern, the example reassigns the original custom format string assigned to the property after the property is modified. ### Change from a 12-hour clock to a 24-hour clock @@ -228,15 +228,15 @@ The `nonHours` capturing group contains the minute and possibly the second compo ### Display and change the era in a date -The following example adds the "g" custom format specifier to the property of an object that represents the formatting conventions of the en-US culture. This addition affects the following three standard format strings: +The following example adds the "g" custom format specifier to the property of an object that represents the formatting conventions of the en-US culture. This addition affects the following three standard format strings: -- The "D" (long date) standard format string, which maps directly to the property. +- The "D" (long date) standard format string, which maps directly to the property. -- The "f" (full date / short time) standard format string, which produces a result string that concatenates the substrings produced by the and properties. +- The "f" (full date / short time) standard format string, which produces a result string that concatenates the substrings produced by the and properties. -- The "F" (full date / long time) standard format string, which maps directly to the property. Because we have not explicitly set this property value, it is generated dynamically by concatenating the and properties. +- The "F" (full date / long time) standard format string, which maps directly to the property. Because we have not explicitly set this property value, it is generated dynamically by concatenating the and properties. -The example also shows how to change the era name for a culture whose calendar has a single era. In this case, the en-US culture uses the Gregorian calendar, which is represented by a object. The class supports a single era, which it names A.D. (Anno Domini). The example changes the era name to C.E. (Common Era) by replacing the "g" custom format specifier in the format string assigned to the property with a literal string. The use of a literal string is necessary, because the era name is typically returned by the method from private data in the culture tables supplied by either .NET or the operating system. +The example also shows how to change the era name for a culture whose calendar has a single era. In this case, the en-US culture uses the Gregorian calendar, which is represented by a object. The class supports a single era, which it names A.D. (Anno Domini). The example changes the era name to C.E. (Common Era) by replacing the "g" custom format specifier in the format string assigned to the property with a literal string. The use of a literal string is necessary, because the era name is typically returned by the method from private data in the culture tables supplied by either .NET or the operating system. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example4.cs" id="Snippet11"::: @@ -246,7 +246,7 @@ Parsing involves converting the string representation of a date and time to a enumeration value to determine which style elements (such as leading, trailing, or inner white space) can be present in the string to be parsed, and how to interpret the parsed string or any missing elements. If you don't provide a value when you call the `Parse` or `TryParse` method, the default is , which is a composite style that includes the , , and flags. For the `ParseExact` and `TryParseExact` methods, the default is ; the input string must correspond precisely to a particular custom date and time format string. -The parsing methods also implicitly or explicitly use a object that defines the specific symbols and patterns that can occur in the string to be parsed. If you don't provide a object, the object for the current culture is used by default. For more information about parsing date and time strings, see the individual parsing methods, such as , , , and . +The parsing methods also implicitly or explicitly use a object that defines the specific symbols and patterns that can occur in the string to be parsed. If you don't provide a object, the object for the current culture is used by default. For more information about parsing date and time strings, see the individual parsing methods, such as , , , and . The following example illustrates the culture-sensitive nature of parsing date and time strings. It tries to parse two date strings by using the conventions of the en-US, en-GB, fr-FR, and fi-FI cultures. The date that is interpreted as 8/18/2014 in the en-US culture throws a exception in the other three cultures because 18 is interpreted as the month number. 1/2/2015 is parsed as the second day of the first month in the en-US culture, but as the first day of the second month in the remaining cultures. @@ -269,7 +269,7 @@ The following example illustrates the difference between a parsing operation tha ### Serialize and deserialize date and time data -Serialized date and time data are expected to round-trip; that is, all serialized and deserialized values should be identical. If a date and time value represents a single moment in time, the deserialized value should represent the same moment in time regardless of the culture or time zone of the system on which it was restored. To round-trip date and time data successfully, you must use the conventions of the invariant culture, which is returned by the property, to generate and parse the data. The formatting and parsing operations should never reflect the conventions of the default culture. If you use default cultural settings, the portability of the data is strictly limited; it can be successfully deserialized only on a thread whose cultural-specific settings are identical to those of the thread on which it was serialized. In some cases, this means that the data cannot even be successfully serialized and deserialized on the same system. +Serialized date and time data are expected to round-trip; that is, all serialized and deserialized values should be identical. If a date and time value represents a single moment in time, the deserialized value should represent the same moment in time regardless of the culture or time zone of the system on which it was restored. To round-trip date and time data successfully, you must use the conventions of the invariant culture, which is returned by the property, to generate and parse the data. The formatting and parsing operations should never reflect the conventions of the default culture. If you use default cultural settings, the portability of the data is strictly limited; it can be successfully deserialized only on a thread whose cultural-specific settings are identical to those of the thread on which it was serialized. In some cases, this means that the data cannot even be successfully serialized and deserialized on the same system. If the time component of a date and time value is significant, it should also be converted to UTC and serialized by using the "o" or "r" [standard format string](../../standard/base-types/standard-date-and-time-format-strings.md). The time data can then be restored by calling a parsing method and passing it the appropriate format string along with the invariant culture as the `provider` argument. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md index 7948067e968e3..ae1fa43a386eb 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md @@ -22,7 +22,7 @@ You can instantiate a object for th - By retrieving the object returned by the `static` (`Shared` in Visual Basic) property. -- By calling the method with a object that represents the current culture. +- By calling the method with a object that represents the current culture. The following example uses these three ways to create objects that represent the formatting conventions of the current culture. It also retrieves the value of the property to illustrate that each object is read-only. @@ -30,9 +30,9 @@ The following example uses these three ways to create object that represents the conventions of the current culture in any of the following ways: -- By retrieving a object in any of the ways illustrated in the previous code example, and calling the method on the returned object. This creates a copy of the original object, except that its property is `false`. +- By retrieving a object in any of the ways illustrated in the previous code example, and calling the method on the returned object. This creates a copy of the original object, except that its property is `false`. -- By calling the method to create a object that represents the current culture, and then using its property to retrieve the object. +- By calling the method to create a object that represents the current culture, and then using its property to retrieve the object. The following example illustrates these two ways of instantiating a object, and displays the value of its property to illustrate that the object is not read-only. @@ -42,7 +42,7 @@ Note that the Windows operating system allows the user to override some of the < :::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/instantiate3.cs" id="Snippet3"::: -If the property is set to `true`, the properties , , and are also retrieved from the user settings. If the user settings are incompatible with the culture associated with the object (for example, if the selected calendar is not one of the calendars listed by the property), the results of the methods and the values of the properties are undefined. +If the property is set to `true`, the properties , , and are also retrieved from the user settings. If the user settings are incompatible with the culture associated with the object (for example, if the selected calendar is not one of the calendars listed by the property), the results of the methods and the values of the properties are undefined. ### Instantiate a NumberFormatInfo object for the invariant culture @@ -52,9 +52,9 @@ You can instantiate a object that r - By retrieving the value of the property. The returned object is read-only. -- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. +- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. -- By calling the parameterless class constructor. The returned object is read/write. +- By calling the parameterless class constructor. The returned object is read/write. The following example uses each of these methods to instantiate a object that represents the invariant culture. It then indicates whether the object is read-only, @@ -64,13 +64,13 @@ The following example uses each of these methods to instantiate a object that represents the formatting conventions of a specific culture in the following ways: -- By calling the method and retrieving the value of the returned object's property. The returned object is read-only. +- By calling the method and retrieving the value of the returned object's property. The returned object is read-only. -- By passing a object that represents the culture whose object you want to retrieve to the static method. The returned object is read/write. +- By passing a object that represents the culture whose object you want to retrieve to the static method. The returned object is read/write. -- By calling the method and retrieving the value of the returned object's property. The returned object is read/write. +- By calling the method and retrieving the value of the returned object's property. The returned object is read/write. -- By calling one of the class constructors and retrieving the value of the returned object's property. The returned object is read/write. +- By calling one of the class constructors and retrieving the value of the returned object's property. The returned object is read/write. The following example uses these four ways to create a object that reflects the formatting conventions of the Indonesian (Indonesia) culture. It also indicates whether each object is read-only. @@ -96,7 +96,7 @@ The culture-specific data for formatting numeric values provided by the data to change. For example, the current culture can be changed either programmatically or through user action. When this happens, the object returned by the property changes to an object associated with the current culture. -- **User preferences.** Users of your application might override some of the values associated with the current system culture through the region and language options in Control Panel. For example, users might choose a different currency symbol or a different decimal separator symbol. If the property is set to `true` (its default value), the properties of the object are also retrieved from the user settings. +- **User preferences.** Users of your application might override some of the values associated with the current system culture through the region and language options in Control Panel. For example, users might choose a different currency symbol or a different decimal separator symbol. If the property is set to `true` (its default value), the properties of the object are also retrieved from the user settings. All user-overridable properties of a object are initialized when the object is created. There is still a possibility of inconsistency, because neither object creation nor the user override process is atomic, and the relevant values may change during object creation. However, these inconsistencies should be extremely rare. @@ -105,11 +105,11 @@ You can control whether user overrides are reflected in property|Yes| -| method|Yes| -| method|No| -| constructor|Yes| -| constructor|Depends on value of `useUserOverride` parameter| +| property|Yes| +| method|Yes| +| method|No| +| constructor|Yes| +| constructor|Depends on value of `useUserOverride` parameter| Unless there is a compelling reason to do otherwise, you should respect user overrides when you use the object in client applications to format and parse user input or to display numeric data. For server applications or unattended applications, you should not respect user overrides. However, if you are using the object either explicitly or implicitly to persist numeric data in string form, you should either use a object that reflects the formatting conventions of the invariant culture, or you should specify a custom numeric format string that you use regardless of culture. @@ -117,21 +117,21 @@ Unless there is a compelling reason to do otherwise, you should respect user ove A object is used implicitly or explicitly in all numeric formatting operations. These include calls to the following methods: -- All numeric formatting methods, such as , , and . +- All numeric formatting methods, such as , , and . -- The major composite formatting method, . +- The major composite formatting method, . -- Other composite formatting methods, such as and . +- Other composite formatting methods, such as and . -All numeric formatting operations make use of an implementation. The interface includes a single method, . This is a callback method that is passed a object that represents the type needed to provide formatting information. The method is responsible for returning either an instance of that type or `null`, if it cannot provide an instance of the type. .NET provides two implementations for formatting numbers: +All numeric formatting operations make use of an implementation. The interface includes a single method, . This is a callback method that is passed a object that represents the type needed to provide formatting information. The method is responsible for returning either an instance of that type or `null`, if it cannot provide an instance of the type. .NET provides two implementations for formatting numbers: -- The class, which represents a specific culture (or a specific language in a specific country/region). In a numeric formatting operation, the method returns the object associated with its property. +- The class, which represents a specific culture (or a specific language in a specific country/region). In a numeric formatting operation, the method returns the object associated with its property. -- The class, which provides information about the formatting conventions of its associated culture. The method returns an instance of itself. +- The class, which provides information about the formatting conventions of its associated culture. The method returns an instance of itself. -If an implementation is not provided to a formatting method explicitly, a object returned by the property that represents the current culture is used. +If an implementation is not provided to a formatting method explicitly, a object returned by the property that represents the current culture is used. -The following example illustrates the relationship between the interface and the class in formatting operations by defining a custom implementation. Its method displays the type name of the object requested by the formatting operation. If the interface is requesting a object, this method provides the object for the current culture. As the output from the example shows, the method requests a object to provide formatting information, whereas the method requests and objects as well as an implementation. +The following example illustrates the relationship between the interface and the class in formatting operations by defining a custom implementation. Its method displays the type name of the object requested by the formatting operation. If the interface is requesting a object, this method provides the object for the current culture. As the output from the example shows, the method requests a object to provide formatting information, whereas the method requests and objects as well as an implementation. :::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/formatprovider1.cs" id="Snippet1"::: @@ -139,7 +139,7 @@ If an implementation is not explicitly provided in ## Format strings and NumberFormatInfo properties -Every formatting operation uses either a standard or a custom numeric format string to produce a result string from a number. In some cases, the use of a format string to produce a result string is explicit, as in the following example. This code calls the method to convert a value to a number of different string representations by using the formatting conventions of the en-US culture. +Every formatting operation uses either a standard or a custom numeric format string to produce a result string from a number. In some cases, the use of a format string to produce a result string is explicit, as in the following example. This code calls the method to convert a value to a number of different string representations by using the formatting conventions of the en-US culture. :::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/properties1.cs" id="Snippet2"::: @@ -151,22 +151,22 @@ Each standard numeric format string uses one or more , to define the default number of fractional digits.

, to define the decimal separator symbol.

, to define the group or thousands separator.

, to define the sizes of integral groups.

, to define the pattern of negative currency values.

, to define the pattern of positive currency values.

, to define the currency symbol.

, to define the negative sign symbol.| -|"D" or "d" (decimal format specifier)|, to define the negative sign symbol.| -|"E" or "e" (exponential or scientific format specifier)|, to define the negative sign symbol in the mantissa and exponent.

, to define the decimal separator symbol.

, to define the positive sign symbol in the exponent.| -|"F" or "f" (fixed-point format specifier)|, to define the negative sign symbol.

, to define the default number of fractional digits.

, to define the decimal separator symbol.| -|"G" or "g" (general format specifier)|, to define the negative sign symbol.

, to define the decimal separator symbol.

, to define the positive sign symbol for result strings in exponential format.| -|"N" or "n" (number format specifier)|, to define the negative sign symbol.

, to define the default number of fractional digits.

, to define the decimal separator symbol.

, to define the group separator (thousands) symbol.

, to define the number of integral digits in a group.

, to define the format of negative values.| -|"P" or "p" (percent format specifier)|, to define the negative sign symbol.

, to define the default number of fractional digits.

, to define the decimal separator symbol.

, to define the group separator symbol.

, to define the number of integral digits in a group.

, to define the placement of the percent symbol and the negative symbol for negative values.

, to define the placement of the percent symbol for positive values.

, to define the percent symbol.| -|"R" or "r" (round-trip format specifier)|, to define the negative sign symbol.

, to define the decimal separator symbol.

, to define the positive sign symbol in an exponent.| +|"C" or "c" (currency format specifier)|, to define the default number of fractional digits.

, to define the decimal separator symbol.

, to define the group or thousands separator.

, to define the sizes of integral groups.

, to define the pattern of negative currency values.

, to define the pattern of positive currency values.

, to define the currency symbol.

, to define the negative sign symbol.| +|"D" or "d" (decimal format specifier)|, to define the negative sign symbol.| +|"E" or "e" (exponential or scientific format specifier)|, to define the negative sign symbol in the mantissa and exponent.

, to define the decimal separator symbol.

, to define the positive sign symbol in the exponent.| +|"F" or "f" (fixed-point format specifier)|, to define the negative sign symbol.

, to define the default number of fractional digits.

, to define the decimal separator symbol.| +|"G" or "g" (general format specifier)|, to define the negative sign symbol.

, to define the decimal separator symbol.

, to define the positive sign symbol for result strings in exponential format.| +|"N" or "n" (number format specifier)|, to define the negative sign symbol.

, to define the default number of fractional digits.

, to define the decimal separator symbol.

, to define the group separator (thousands) symbol.

, to define the number of integral digits in a group.

, to define the format of negative values.| +|"P" or "p" (percent format specifier)|, to define the negative sign symbol.

, to define the default number of fractional digits.

, to define the decimal separator symbol.

, to define the group separator symbol.

, to define the number of integral digits in a group.

, to define the placement of the percent symbol and the negative symbol for negative values.

, to define the placement of the percent symbol for positive values.

, to define the percent symbol.| +|"R" or "r" (round-trip format specifier)|, to define the negative sign symbol.

, to define the decimal separator symbol.

, to define the positive sign symbol in an exponent.| |"X" or "x" (hexadecimal format specifier)|None.| -|"." (decimal point custom format specifier)|, to define the decimal separator symbol.| -|"," (group separator custom format specifier)|, to define the group (thousands) separator symbol.| -|"%" (percentage placeholder custom format specifier)|, to define the percent symbol.| -|"‰" (per mille placeholder custom format specifier)|, to define the per mille symbol.| -|"E" (exponential notation custom format specifier)|, to define the negative sign symbol in the mantissa and exponent.

, to define the positive sign symbol in the exponent.| +|"." (decimal point custom format specifier)|, to define the decimal separator symbol.| +|"," (group separator custom format specifier)|, to define the group (thousands) separator symbol.| +|"%" (percentage placeholder custom format specifier)|, to define the percent symbol.| +|"‰" (per mille placeholder custom format specifier)|, to define the per mille symbol.| +|"E" (exponential notation custom format specifier)|, to define the negative sign symbol in the mantissa and exponent.

, to define the positive sign symbol in the exponent.| -Note that the class includes a property that specifies the base 10 digits used by a specific culture. However, the property is not used in formatting operations; only the Basic Latin digits 0 (U+0030) through 9 (U+0039) are used in the result string. In addition, for and values of `NaN`, `PositiveInfinity`, and `NegativeInfinity`, the result string consists exclusively of the symbols defined by the , , and properties, respectively. +Note that the class includes a property that specifies the base 10 digits used by a specific culture. However, the property is not used in formatting operations; only the Basic Latin digits 0 (U+0030) through 9 (U+0039) are used in the result string. In addition, for and values of `NaN`, `PositiveInfinity`, and `NegativeInfinity`, the result string consists exclusively of the symbols defined by the , , and properties, respectively. ## Modify NumberFormatInfo properties @@ -201,7 +201,7 @@ Parsing involves converting the string representation of a number to a number. E The parsing methods implicitly or explicitly use a enumeration value to determine what style elements (such as group separators, a decimal separator, or a currency symbol) can be present in a string if the parsing operation is to succeed. If a value is not provided in the method call, the default is a value that includes the and flags, which specifies that the parsed string can include group symbols, a decimal separator, a negative sign, and white-space characters, or it can be the string representation of a number in exponential notation. -The parsing methods also implicitly or explicitly use a object that defines the specific symbols and patterns that can occur in the string to be parsed. If a object is not provided, the default is the for the current culture. For more information about parsing, see the individual parsing methods, such as , , , , , and . +The parsing methods also implicitly or explicitly use a object that defines the specific symbols and patterns that can occur in the string to be parsed. If a object is not provided, the default is the for the current culture. For more information about parsing, see the individual parsing methods, such as , , , , , and . The following example illustrates the culture-sensitive nature of parsing strings. It tries to parse a string that include thousands separators by using the conventions of the en-US, fr-FR, and invariant cultures. A string that includes the comma as a group separator and the period as a decimal separator fails to parse in the fr-FR culture, and a string with white space as a group separator and a comma as a decimal separator fails to parse in the en-US and invariant cultures. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-persiancalendar.md b/docs/fundamentals/runtime-libraries/system-globalization-persiancalendar.md index 9bfc3e59e7d25..7ecf67746eef4 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-persiancalendar.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-persiancalendar.md @@ -29,7 +29,7 @@ As a result of the changed algorithm: - The two algorithms might return different results when converting dates before 1800 and after 2123 in the Gregorian calendar. - The property value has changed from March 21, 0622 in the Gregorian calendar to March 22, 0622 in the Gregorian calendar. - The property value has changed from the 10th day of the 10th month of the year 9378 in the Persian calendar to the 13th day of the 10th month of the year 9378 in the Persian calendar. -- The method might return a different result than it did previously. +- The method might return a different result than it did previously. ## Use the PersianCalendar class diff --git a/docs/fundamentals/runtime-libraries/system-globalization-regioninfo.md b/docs/fundamentals/runtime-libraries/system-globalization-regioninfo.md index 56f65d756666e..e75dd5afb822e 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-regioninfo.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-regioninfo.md @@ -35,4 +35,4 @@ In scenarios such as the following, use culture names instead of country/region | | `US Dollar` | `US Dollar` | `Dólar de EE.UU.` | | | `US` | `en-US` | `es-US` | | | `United States` | `United States` | `Estados Unidos` | - | | `US` | `en-US` | `es-US` | + | | `US` | `en-US` | `es-US` | diff --git a/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md b/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md index 4599f84e597af..0c3301a90dca5 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md @@ -10,34 +10,34 @@ ms.topic: concept-article A culture-sensitive comparison of two strings depends on each character in the strings having several categories of sort weights, including script, alphabetic, case, and diacritic weights. A sort key serves as the repository of these weights for a particular string. -The method returns an instance of the class that reflects the culture-sensitive mapping of characters in a specified string. The value of a object is its key data, which is returned by the property. This key data consists of a series of bytes that encode the string, culture-specific sorting rules, and user-specified comparison options. A comparison using sort keys consists of a bitwise comparison of the corresponding key data in each sort key. For example, if you create a sort key by calling the method with a value of , a string comparison operation that uses the sort key is case-insensitive. +The method returns an instance of the class that reflects the culture-sensitive mapping of characters in a specified string. The value of a object is its key data, which is returned by the property. This key data consists of a series of bytes that encode the string, culture-specific sorting rules, and user-specified comparison options. A comparison using sort keys consists of a bitwise comparison of the corresponding key data in each sort key. For example, if you create a sort key by calling the method with a value of , a string comparison operation that uses the sort key is case-insensitive. -After you create a sort key for a string, you compare sort keys by calling the static method. This method performs a simple byte-by-byte comparison, so it is much faster than the or method. +After you create a sort key for a string, you compare sort keys by calling the static method. This method performs a simple byte-by-byte comparison, so it is much faster than the or method. > [!NOTE] > You can download the [Sorting Weight Tables](https://www.microsoft.com/download/details.aspx?id=10921), a set of text files that contain information on the character weights used in sorting and comparison operations for Windows operating systems, the [Default Unicode Collation Element Table](https://www.unicode.org/Public/UCA/latest/allkeys.txt), the sort weight table for Linux and macOS. ## Performance considerations -When performing a string comparison, the and methods yield the same results, but they target different scenarios. +When performing a string comparison, the and methods yield the same results, but they target different scenarios. -At a high level, the method generates the sort key for each string, performs the comparison, and then discards the sort key and returns the result of the comparison. However, the method actually doesn't generate an entire sort key to perform the comparison. Instead, the method generates the key data for each text element (that is, base character, surrogate pair, or combining character sequence) in each string. The method then compares the key data for the corresponding text elements. The operation terminates as soon as the ultimate result of the comparison is determined. Sort key information is computed, but no object is created. This strategy is economical in terms of performance if both strings are compared once, but becomes expensive if the same strings are compared many times. +At a high level, the method generates the sort key for each string, performs the comparison, and then discards the sort key and returns the result of the comparison. However, the method actually doesn't generate an entire sort key to perform the comparison. Instead, the method generates the key data for each text element (that is, base character, surrogate pair, or combining character sequence) in each string. The method then compares the key data for the corresponding text elements. The operation terminates as soon as the ultimate result of the comparison is determined. Sort key information is computed, but no object is created. This strategy is economical in terms of performance if both strings are compared once, but becomes expensive if the same strings are compared many times. -The method requires generation of a object for each string before performing the comparison. This strategy is expensive in terms of performance for the first comparison because of the time and memory invested to generate the objects. However, it becomes economical if the same sort keys are compared many times. +The method requires generation of a object for each string before performing the comparison. This strategy is expensive in terms of performance for the first comparison because of the time and memory invested to generate the objects. However, it becomes economical if the same sort keys are compared many times. For example, suppose you write an application that searches a database table for the row in which the string-based index column matches a specified search string. The table contains thousands of rows, and comparing the search string to the index in each row will take a long time. Therefore, when the application stores a row and its index column, it also generates and stores the sort key for the index in a column dedicated to improving search performance. When the application searches for a target row, it compares the sort key for the search string to the sort key for the index string, instead of comparing the search string to the index string. ## Security considerations -The method returns a object with the value based on a specified string and value, and the culture associated with the underlying object. If a security decision depends on a string comparison or case change, you should use the method of the invariant culture to ensure that the behavior of the operation is consistent, regardless of the culture settings of the operating system. +The method returns a object with the value based on a specified string and value, and the culture associated with the underlying object. If a security decision depends on a string comparison or case change, you should use the method of the invariant culture to ensure that the behavior of the operation is consistent, regardless of the culture settings of the operating system. Use the following steps to obtain a sort key: 1. Retrieve the invariant culture from the property. -2. Retrieve a object for the invariant culture from the property. +2. Retrieve a object for the invariant culture from the property. -3. Call the method. +3. Call the method. Working with the value of a object is equivalent to calling the Windows `LCMapString` method with the LCMAP_SORTKEY value specified. However, for the object, the sort keys for English characters precede the sort keys for Korean characters. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md b/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md index 5859726b6d155..2db021718dff9 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md @@ -35,16 +35,16 @@ The class provides information about the You can instantiate a object in two ways: -- By calling the constructor, which instantiates a new object based on a version number and sort ID. This constructor is most useful when recreating a object from saved data. -- By retrieving the value of the property. This property provides information about the Unicode version used by the .NET implementation on which the application is running. +- By calling the constructor, which instantiates a new object based on a version number and sort ID. This constructor is most useful when recreating a object from saved data. +- By retrieving the value of the property. This property provides information about the Unicode version used by the .NET implementation on which the application is running. -The class has two properties, and , that indicate the Unicode version and the specific culture used for string comparison. The property is an arbitrary numeric value that reflects the Unicode version used for string comparison, and the property is an arbitrary that reflects the culture whose conventions are used for string comparison. The values of these two properties are important only when you compare two objects by using the method, the operator, or the operator. +The class has two properties, and , that indicate the Unicode version and the specific culture used for string comparison. The property is an arbitrary numeric value that reflects the Unicode version used for string comparison, and the property is an arbitrary that reflects the culture whose conventions are used for string comparison. The values of these two properties are important only when you compare two objects by using the method, the operator, or the operator. You typically use a object when saving or retrieving some form of culture-sensitive, ordered string data, such as indexes or the literal strings themselves. This requires the following steps: -1. When the ordered string data is saved, the and property values are also saved. +1. When the ordered string data is saved, the and property values are also saved. -2. When the ordered string data is retrieved, you can recreate the object used for ordering the strings by calling the constructor. +2. When the ordered string data is retrieved, you can recreate the object used for ordering the strings by calling the constructor. 3. This newly instantiated object is compared with a object that reflects the culture whose conventions are used to order the string data. diff --git a/docs/fundamentals/runtime-libraries/system-iasyncdisposable.md b/docs/fundamentals/runtime-libraries/system-iasyncdisposable.md index 69462ebd94989..afe1a7ee99165 100644 --- a/docs/fundamentals/runtime-libraries/system-iasyncdisposable.md +++ b/docs/fundamentals/runtime-libraries/system-iasyncdisposable.md @@ -9,13 +9,13 @@ ms.date: 12/31/2023 In .NET, classes that own unmanaged resources usually implement the interface to provide a mechanism for releasing unmanaged resources synchronously. However, in some cases they need to provide an asynchronous mechanism for releasing unmanaged resources in addition to (or instead of) the synchronous one. Providing such a mechanism enables the consumer to perform resource-intensive dispose operations without blocking the main thread of a GUI application for a long time. -The method of this interface returns a that represents the asynchronous dispose operation. Classes that own unmanaged resources implement this method, and the consumer of these classes calls this method on an object when it is no longer needed. +The method of this interface returns a that represents the asynchronous dispose operation. Classes that own unmanaged resources implement this method, and the consumer of these classes calls this method on an object when it is no longer needed. The async methods are used in conjunction with the `async` and `await` keywords in C# and Visual Basic. For more information, see [The Task asynchronous programming model in C#](/dotnet/csharp/programming-guide/concepts/async/index) or [Asynchronous Programming with Async and Await (Visual Basic)](../../visual-basic/programming-guide/concepts/async/index.md). ## Use an object that implements IAsyncDisposable -If your application uses an object that implements `IAsyncDisposable`, you should call the object's implementation when you are finished using it. To make sure resources are released even in case of an exception, put the code that uses the `IAsyncDisposable` object into the [using](../../csharp/language-reference/keywords/using.md) statement (in C# beginning from version 8.0) or call the method inside a `finally` clause of the `try`/`finally` statement. For more information about the `try`/`finally` pattern, see [try-finally](/dotnet/csharp/language-reference/keywords/try-finally) (C#) or [Try...Catch...Finally Statement](../../visual-basic/language-reference/statements/try-catch-finally-statement.md) (Visual Basic). +If your application uses an object that implements `IAsyncDisposable`, you should call the object's implementation when you are finished using it. To make sure resources are released even in case of an exception, put the code that uses the `IAsyncDisposable` object into the [using](../../csharp/language-reference/keywords/using.md) statement (in C# beginning from version 8.0) or call the method inside a `finally` clause of the `try`/`finally` statement. For more information about the `try`/`finally` pattern, see [try-finally](/dotnet/csharp/language-reference/keywords/try-finally) (C#) or [Try...Catch...Finally Statement](../../visual-basic/language-reference/statements/try-catch-finally-statement.md) (Visual Basic). ## Implement IAsyncDisposable @@ -24,4 +24,4 @@ You might implement `IAsyncDisposable` in the following situations: - When developing an asynchronous enumerator that owns unmanaged resources. Asynchronous enumerators are used with the C# 8.0 async streams feature. For more information about async streams, see [Tutorial: Generate and consume async streams using C# 8.0 and .NET Core 3.0](/dotnet/csharp/tutorials/generate-consume-asynchronous-stream). - When your class owns unmanaged resources and releasing them requires a resource-intensive I/O operation, such as flushing the contents of an intermediate buffer into a file or sending a packet over a network to close a connection. -Use the method to perform whatever cleanup is necessary after using the unmanaged resources, such as freeing, releasing, or resetting the unmanaged resources. For more information, see [Implement a DisposeAsync method](../../standard/garbage-collection/implementing-disposeasync.md). +Use the method to perform whatever cleanup is necessary after using the unmanaged resources, such as freeing, releasing, or resetting the unmanaged resources. For more information, see [Implement a DisposeAsync method](../../standard/garbage-collection/implementing-disposeasync.md). diff --git a/docs/fundamentals/runtime-libraries/system-idisposable.md b/docs/fundamentals/runtime-libraries/system-idisposable.md index 26765cee858fa..16baa7d24877e 100644 --- a/docs/fundamentals/runtime-libraries/system-idisposable.md +++ b/docs/fundamentals/runtime-libraries/system-idisposable.md @@ -13,31 +13,31 @@ dev_langs: The primary use of the interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it's not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams. -Use the method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed. +Use the method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed. > [!WARNING] -> It is a breaking change to add the interface to an existing class. Because pre-existing consumers of your type cannot call , you cannot be certain that unmanaged resources held by your type will be released. +> It is a breaking change to add the interface to an existing class. Because pre-existing consumers of your type cannot call , you cannot be certain that unmanaged resources held by your type will be released. -Because the implementation is called by the consumer of a type when the resources owned by an instance are no longer needed, you should either wrap the managed object in a (the recommended alternative), or you should override to free unmanaged resources in the event that the consumer forgets to call . +Because the implementation is called by the consumer of a type when the resources owned by an instance are no longer needed, you should either wrap the managed object in a (the recommended alternative), or you should override to free unmanaged resources in the event that the consumer forgets to call . > [!IMPORTANT] -> In .NET Framework, the C++ compiler supports deterministic disposal of resources and does not allow direct implementation of the method. +> In .NET Framework, the C++ compiler supports deterministic disposal of resources and does not allow direct implementation of the method. -For a detailed discussion about how this interface and the method are used, see the [Garbage Collection](../../standard/garbage-collection/index.md) and [Implementing a Dispose Method](../../standard/garbage-collection/implementing-dispose.md) topics. +For a detailed discussion about how this interface and the method are used, see the [Garbage Collection](../../standard/garbage-collection/index.md) and [Implementing a Dispose Method](../../standard/garbage-collection/implementing-dispose.md) topics. ## Use an object that implements IDisposable -If your app simply uses an object that implements the interface, you should call the object's implementation when you are finished using it. Depending on your programming language, you can do this in one of two ways: +If your app simply uses an object that implements the interface, you should call the object's implementation when you are finished using it. Depending on your programming language, you can do this in one of two ways: - By using a language construct such as the `using` statement in C# and Visual Basic, and the `use` statement or `using` function in F#. -- By wrapping the call to the implementation in a `try`/`finally` block. +- By wrapping the call to the implementation in a `try`/`finally` block. > [!NOTE] -> Documentation for types that implement note that fact and include a reminder to call its implementation. +> Documentation for types that implement note that fact and include a reminder to call its implementation. ### The C#, F#, and Visual Basic Using statement -If your language supports a construct such as the [using](../../csharp/language-reference/keywords/using.md) statement in C#, the [Using](../../visual-basic/language-reference/statements/using-statement.md) statement in Visual Basic, or the [use](../../fsharp/language-reference/resource-management-the-use-keyword.md) statement in F#, you can use it instead of explicitly calling yourself. The following example uses this approach in defining a `WordCount` class that preserves information about a file and the number of words in it. +If your language supports a construct such as the [using](../../csharp/language-reference/keywords/using.md) statement in C#, the [Using](../../visual-basic/language-reference/statements/using-statement.md) statement in Visual Basic, or the [use](../../fsharp/language-reference/resource-management-the-use-keyword.md) statement in F#, you can use it instead of explicitly calling yourself. The following example uses this approach in defining a `WordCount` class that preserves information about a file and the number of words in it. :::code language="csharp" source="./snippets/System/IDisposable/Overview/csharp/calling1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/IDisposable/Overview/fsharp/calling1.fs" id="Snippet1"::: @@ -49,7 +49,7 @@ For more information about the `using` statement, see the [Using Statement](../. ### The Try/Finally block -If your programming language does not support a construct like the `using` statement in C# or Visual Basic, or the `use` statement in F#, or if you prefer not to use it, you can call the implementation from the `finally` block of a `try`/`finally` statement. The following example replaces the `using` block in the previous example with a `try`/`finally` block. +If your programming language does not support a construct like the `using` statement in C# or Visual Basic, or the `use` statement in F#, or if you prefer not to use it, you can call the implementation from the `finally` block of a `try`/`finally` statement. The following example replaces the `using` block in the previous example with a `try`/`finally` block. :::code language="csharp" source="./snippets/System/IDisposable/Overview/csharp/calling2.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/IDisposable/Overview/fsharp/calling2.fs" id="Snippet2"::: @@ -59,10 +59,10 @@ For more information about the `try`/`finally` pattern, see [Try...Catch...Final ## Implement IDisposable -You should implement if your type uses unmanaged resources directly or if you wish to use disposable resources yourself. The consumers of your type can call your implementation to free resources when the instance is no longer needed. To handle cases in which they fail to call , you should either use a class derived from to wrap the unmanaged resources, or you should override the method for a reference type. In either case, you use the method to perform whatever cleanup is necessary after using the unmanaged resources, such as freeing, releasing, or resetting the unmanaged resources. For more information about implementing , see [the Dispose(bool) method overload](../../standard/garbage-collection/implementing-dispose.md#the-disposebool-method-overload). +You should implement if your type uses unmanaged resources directly or if you wish to use disposable resources yourself. The consumers of your type can call your implementation to free resources when the instance is no longer needed. To handle cases in which they fail to call , you should either use a class derived from to wrap the unmanaged resources, or you should override the method for a reference type. In either case, you use the method to perform whatever cleanup is necessary after using the unmanaged resources, such as freeing, releasing, or resetting the unmanaged resources. For more information about implementing , see [the Dispose(bool) method overload](../../standard/garbage-collection/implementing-dispose.md#the-disposebool-method-overload). > [!IMPORTANT] -> If you are defining a base class that uses unmanaged resources and that either has, or is likely to have, subclasses that should be disposed, you should implement the method and provide a second overload of `Dispose`, as discussed in the next section. +> If you are defining a base class that uses unmanaged resources and that either has, or is likely to have, subclasses that should be disposed, you should implement the method and provide a second overload of `Dispose`, as discussed in the next section. ## IDisposable and the inheritance hierarchy @@ -72,13 +72,13 @@ A base class with subclasses that should be disposable must implement method must call `Dispose(true)` and should suppress finalization for performance. - The base type should not include any finalizers. -The following code fragment reflects the dispose pattern for base classes. It assumes that your type does not override the method. +The following code fragment reflects the dispose pattern for base classes. It assumes that your type does not override the method. :::code language="csharp" source="./snippets/System/IDisposable/Overview/csharp/base1.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/IDisposable/Overview/fsharp/base1.fs" id="Snippet3"::: :::code language="vb" source="./snippets/System/IDisposable/Overview/vb/base1.vb" id="Snippet3"::: -If you do override the method, your class should implement the following pattern. +If you do override the method, your class should implement the following pattern. :::code language="csharp" source="./snippets/System/IDisposable/Overview/csharp/base2.cs" id="Snippet5"::: :::code language="fsharp" source="./snippets/System/IDisposable/Overview/fsharp/base2.fs" id="Snippet5"::: @@ -89,9 +89,9 @@ Subclasses should implement the disposable pattern as follows: - They must override `Dispose(Boolean)` and call the base class `Dispose(Boolean)` implementation. - They can provide a finalizer if needed. The finalizer must call `Dispose(false)`. -Note that derived classes do not themselves implement the interface and do not include a parameterless method. They only override the base class `Dispose(Boolean)` method. +Note that derived classes do not themselves implement the interface and do not include a parameterless method. They only override the base class `Dispose(Boolean)` method. -The following code fragment reflects the dispose pattern for derived classes. It assumes that your type does not override the method. +The following code fragment reflects the dispose pattern for derived classes. It assumes that your type does not override the method. :::code language="csharp" source="./snippets/System/IDisposable/Overview/csharp/derived1.cs" id="Snippet4"::: :::code language="fsharp" source="./snippets/System/IDisposable/Overview/fsharp/derived1.fs" id="Snippet4"::: diff --git a/docs/fundamentals/runtime-libraries/system-int32.md b/docs/fundamentals/runtime-libraries/system-int32.md index cf120220ee3a4..b42dcb17c7562 100644 --- a/docs/fundamentals/runtime-libraries/system-int32.md +++ b/docs/fundamentals/runtime-libraries/system-int32.md @@ -41,7 +41,7 @@ You can instantiate an value in several ways: :::code language="fsharp" source="./snippets/System/Int32/Overview/fsharp/toint32_1.fs" id="Snippet4"::: :::code language="vb" source="./snippets/System/Convert/Overview/vb/toint32_1.vb" id="Snippet4"::: -- You can call the or method to convert the string representation of an value to an . The string can contain either decimal or hexadecimal digits. The following example illustrates the parse operation by using both a decimal and a hexadecimal string. +- You can call the or method to convert the string representation of an value to an . The string can contain either decimal or hexadecimal digits. The following example illustrates the parse operation by using both a decimal and a hexadecimal string. :::code language="csharp" source="./snippets/System/Int32/Overview/csharp/Instantiate1.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/Int32/Overview/fsharp/Instantiate1.fs" id="Snippet3"::: @@ -51,7 +51,7 @@ You can instantiate an value in several ways: The type supports standard mathematical operations such as addition, subtraction, division, multiplication, negation, and unary negation. Like the other integral types, the type also supports the bitwise `AND`, `OR`, `XOR`, left shift, and right shift operators. -You can use the standard numeric operators to compare two values, or you can call the or method. +You can use the standard numeric operators to compare two values, or you can call the or method. You can also call the members of the class to perform a wide range of numeric operations, including getting the absolute value of a number, calculating the quotient and remainder from integral division, determining the maximum or minimum value of two integers, getting the sign of a number, and rounding a number. @@ -65,7 +65,7 @@ To format an value as an integral string with no leading zer :::code language="fsharp" source="./snippets/System/Int32/Overview/fsharp/Formatting1.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/Int32/Overview/vb/Formatting1.vb" id="Snippet1"::: -You can also format an value as a binary, octal, decimal, or hexadecimal string by calling the method and supplying the base as the method's second parameter. The following example calls this method to display the binary, octal, and hexadecimal representations of an array of integer values. +You can also format an value as a binary, octal, decimal, or hexadecimal string by calling the method and supplying the base as the method's second parameter. The following example calls this method to display the binary, octal, and hexadecimal representations of an array of integer values. :::code language="csharp" source="./snippets/System/Int32/Overview/csharp/Formatting1.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/Int32/Overview/fsharp/Formatting1.fs" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-int64.md b/docs/fundamentals/runtime-libraries/system-int64.md index a9706def34f1d..04df783a373bc 100644 --- a/docs/fundamentals/runtime-libraries/system-int64.md +++ b/docs/fundamentals/runtime-libraries/system-int64.md @@ -41,7 +41,7 @@ You can instantiate an value in several ways: :::code language="fsharp" source="./snippets/System/Convert/ToInt64/fsharp/toint64_1.fs" id="Snippet4"::: :::code language="vb" source="./snippets/System/Convert/Overview/vb/toint64_1.vb" id="Snippet4"::: -- You can call the or method to convert the string representation of an value to an . The string can contain either decimal or hexadecimal digits. The following example illustrates the parse operation by using both a decimal and a hexadecimal string. +- You can call the or method to convert the string representation of an value to an . The string can contain either decimal or hexadecimal digits. The following example illustrates the parse operation by using both a decimal and a hexadecimal string. :::code language="csharp" source="./snippets/System/Int64/Overview/csharp/instantiate1.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/Int64/Overview/fsharp/instantiate1.fs" id="Snippet3"::: @@ -51,7 +51,7 @@ You can instantiate an value in several ways: The type supports standard mathematical operations such as addition, subtraction, division, multiplication, negation, and unary negation. Like the other integral types, the type also supports the bitwise `AND`, `OR`, `XOR`, left shift, and right shift operators. -You can use the standard numeric operators to compare two values, or you can call the or method. +You can use the standard numeric operators to compare two values, or you can call the or method. You can also call the members of the class to perform a wide range of numeric operations, including getting the absolute value of a number, calculating the quotient and remainder from integral division, determining the maximum or minimum value of two long integers, getting the sign of a number, and rounding a number. @@ -65,7 +65,7 @@ To format an value as an integral string with no leading zer :::code language="fsharp" source="./snippets/System/Convert/ToInt64/fsharp/formatting1.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/Int64/Overview/vb/formatting1.vb" id="Snippet1"::: -You can also format an value as a binary, octal, decimal, or hexadecimal string by calling the method and supplying the base as the method's second parameter. The following example calls this method to display the binary, octal, and hexadecimal representations of an array of integer values. +You can also format an value as a binary, octal, decimal, or hexadecimal string by calling the method and supplying the base as the method's second parameter. The following example calls this method to display the binary, octal, and hexadecimal representations of an array of integer values. :::code language="csharp" source="./snippets/System/Int64/Overview/csharp/formatting1.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/Convert/ToInt64/fsharp/formatting1.fs" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-invalidcastexception.md b/docs/fundamentals/runtime-libraries/system-invalidcastexception.md index 5ff277268ac5f..7f301fedfb00b 100644 --- a/docs/fundamentals/runtime-libraries/system-invalidcastexception.md +++ b/docs/fundamentals/runtime-libraries/system-invalidcastexception.md @@ -32,11 +32,11 @@ The following intermediate language (IL) instructions throw an uses the HRESULT `COR_E_INVALIDCAST`, which has the value 0x80004002. -For a list of initial property values for an instance of , see the constructors. +For a list of initial property values for an instance of , see the constructors. ## Primitive types and IConvertible -You directly or indirectly call a primitive type's implementation that does not support a particular conversion. For example, trying to convert a value to a or a value to an throws an exception. The following example calls both the and methods to convert a value to a . In both cases, the method call throws an exception. +You directly or indirectly call a primitive type's implementation that does not support a particular conversion. For example, trying to convert a value to a or a value to an throws an exception. The following example calls both the and methods to convert a value to a . In both cases, the method call throws an exception. :::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/iconvertible1.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/iconvertible1.fs" id="Snippet2"::: @@ -46,7 +46,7 @@ Because the conversion is not supported, there is no workaround. ## The Convert.ChangeType method -You've called the method to convert an object from one type to another, but one or both types don't implement the interface. +You've called the method to convert an object from one type to another, but one or both types don't implement the interface. In most cases, because the conversion is not supported, there is no workaround. In some cases, a possible workaround is to manually assign property values from the source type to similar properties of a the target type. @@ -88,7 +88,7 @@ You're trying to convert a value or an object to its string representation by us > [!NOTE] > Using the Visual Basic `CStr` operator to convert a value of a primitive type to a string succeeds. The operation does not throw an exception. -To successfully convert an instance of any type to its string representation, call its `ToString` method, as the following example does. The `ToString` method is always present, since the method is defined by the class and therefore is either inherited or overridden by all managed types. +To successfully convert an instance of any type to its string representation, call its `ToString` method, as the following example does. The `ToString` method is always present, since the method is defined by the class and therefore is either inherited or overridden by all managed types. :::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/ToString2.cs" id="Snippet5"::: :::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/ToString2.fs" id="Snippet5"::: diff --git a/docs/fundamentals/runtime-libraries/system-invalidoperationexception.md b/docs/fundamentals/runtime-libraries/system-invalidoperationexception.md index 4d6ae247ffd2a..63fd9c1318752 100644 --- a/docs/fundamentals/runtime-libraries/system-invalidoperationexception.md +++ b/docs/fundamentals/runtime-libraries/system-invalidoperationexception.md @@ -13,9 +13,9 @@ dev_langs: is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Typically, it's thrown when the state of an object cannot support the method call. For example, an exception is thrown by methods such as: -- if objects of a collection are modified after the enumerator is created. For more information, see [Changing a collection while iterating it](#changing-a-collection-while-iterating-it). -- if the resource set is closed before the method call is made. -- , if the object or objects to be added would result in an incorrectly structured XML document. +- if objects of a collection are modified after the enumerator is created. For more information, see [Changing a collection while iterating it](#changing-a-collection-while-iterating-it). +- if the resource set is closed before the method call is made. +- , if the object or objects to be added would result in an incorrectly structured XML document. - A method that attempts to manipulate the UI from a thread that is not the main or UI thread. > [!IMPORTANT] @@ -23,7 +23,7 @@ dev_langs: uses the HRESULT `COR_E_INVALIDOPERATION`, which has the value 0x80131509. -For a list of initial property values for an instance of , see the constructors. +For a list of initial property values for an instance of , see the constructors. ## Common causes of InvalidOperationException exceptions @@ -41,9 +41,9 @@ Often, worker threads are used to perform some background work that involves gat UI frameworks for .NET implement a *dispatcher* pattern that includes a method to check whether a call to a member of a UI element is being executed on the UI thread, and other methods to schedule the call on the UI thread: -- In WPF apps, call the method to determine if a method is running on a non-UI thread. It returns `true` if the method is running on the UI thread and `false` otherwise. Call one of the overloads of the method to schedule the call on the UI thread. -- In UWP apps, check the property to determine if a method is running on a non-UI thread. Call the method to execute a delegate that updates the UI thread. -- In Windows Forms apps, use the property to determine if a method is running on a non-UI thread. Call one of the overloads of the method to execute a delegate that updates the UI thread. +- In WPF apps, call the method to determine if a method is running on a non-UI thread. It returns `true` if the method is running on the UI thread and `false` otherwise. Call one of the overloads of the method to schedule the call on the UI thread. +- In UWP apps, check the property to determine if a method is running on a non-UI thread. Call the method to execute a delegate that updates the UI thread. +- In Windows Forms apps, use the property to determine if a method is running on a non-UI thread. Call one of the overloads of the method to execute a delegate that updates the UI thread. The following examples illustrate the exception that is thrown when you attempt to update a UI element from a thread other than the thread that created it. Each example requires that you create two controls: @@ -74,7 +74,7 @@ The following version of the `DoSomeWork` method eliminates the exception in a W The `foreach` statement in C#, `for...in` in F#, or `For Each` statement in Visual Basic is used to iterate the members of a collection and to read or modify its individual elements. However, it can't be used to add or remove items from the collection. Doing this throws an exception with a message that is similar to, "**Collection was modified; enumeration operation may not execute.**" -The following example iterates a collection of integers attempts to add the square of each integer to the collection. The example throws an with the first call to the method. +The following example iterates a collection of integers attempts to add the square of each integer to the collection. The example throws an with the first call to the method. :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Iterating1.fs" id="Snippet1"::: @@ -98,7 +98,7 @@ You can eliminate the exception in one of two ways, depending on your applicatio ### Sorting an array or collection whose objects cannot be compared -General-purpose sorting methods, such as the method or the method, usually require that at least one of the objects to be sorted implement the or the interface. If not, the collection or array cannot be sorted, and the method throws an exception. The following example defines a `Person` class, stores two `Person` objects in a generic object, and attempts to sort them. As the output from the example shows, the call to the method throws an . +General-purpose sorting methods, such as the method or the method, usually require that at least one of the objects to be sorted implement the or the interface. If not, the collection or array cannot be sorted, and the method throws an exception. The following example defines a `Person` class, stores two `Person` objects in a generic object, and attempts to sort them. As the output from the example shows, the call to the method throws an . :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort1.cs" id="Snippet12"::: :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort1.fs" id="Snippet12"::: @@ -106,23 +106,23 @@ General-purpose sorting methods, such as the or the interface. This requires that you implement either the or the method. Adding an interface implementation to an existing type is not a breaking change. +- If you can own the type that you are trying to sort (that is, if you control its source code), you can modify it to implement the or the interface. This requires that you implement either the or the method. Adding an interface implementation to an existing type is not a breaking change. - The following example uses this approach to provide an implementation for the `Person` class. You can still call the collection or array's general sorting method and, as the output from the example shows, the collection sorts successfully. + The following example uses this approach to provide an implementation for the `Person` class. You can still call the collection or array's general sorting method and, as the output from the example shows, the collection sorts successfully. :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort2.cs" id="Snippet13"::: :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort2.fs" id="Snippet13"::: :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/List_Sort2.vb" id="Snippet13"::: -- If you cannot modify the source code for the type you are trying to sort, you can define a special-purpose sorting class that implements the interface. You can call an overload of the `Sort` method that includes an parameter. This approach is especially useful if you want to develop a specialized sorting class that can sort objects based on multiple criteria. +- If you cannot modify the source code for the type you are trying to sort, you can define a special-purpose sorting class that implements the interface. You can call an overload of the `Sort` method that includes an parameter. This approach is especially useful if you want to develop a specialized sorting class that can sort objects based on multiple criteria. - The following example uses the approach by developing a custom `PersonComparer` class that is used to sort `Person` collections. It then passes an instance of this class to the method. + The following example uses the approach by developing a custom `PersonComparer` class that is used to sort `Person` collections. It then passes an instance of this class to the method. :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort3.cs" id="Snippet14"::: :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort3.fs" id="Snippet14"::: :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/List_Sort3.vb" id="Snippet14"::: -- If you cannot modify the source code for the type you are trying to sort, you can create a delegate to perform the sorting. The delegate signature is +- If you cannot modify the source code for the type you are trying to sort, you can create a delegate to perform the sorting. The delegate signature is ```vb Function Comparison(Of T)(x As T, y As T) As Integer @@ -132,7 +132,7 @@ You can eliminate the exception in any of three ways: int Comparison(T x, T y) ``` - The following example uses the approach by defining a `PersonComparison` method that matches the delegate signature. It then passes this delegate to the method. + The following example uses the approach by defining a `PersonComparison` method that matches the delegate signature. It then passes this delegate to the method. :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort4.cs" id="Snippet15"::: :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort4.fs" id="Snippet15"::: @@ -140,7 +140,7 @@ You can eliminate the exception in any of three ways: ### Casting a Nullable\ that's null to its underlying type -Attempting to cast a value that is `null` to its underlying type throws an exception and displays the error message, "**Nullable object must have a value.** +Attempting to cast a value that is `null` to its underlying type throws an exception and displays the error message, "**Nullable object must have a value.** The following example throws an exception when it attempts to iterate an array that includes a `Nullable(Of Integer)` value. @@ -150,8 +150,8 @@ The following example throws an exceptio To prevent the exception: -- Use the property to select only those elements that are not `null`. -- Call one of the overloads to provide a default value for a `null` value. +- Use the property to select only those elements that are not `null`. +- Call one of the overloads to provide a default value for a `null` value. The following example does both to avoid the exception. @@ -161,7 +161,7 @@ The following example does both to avoid the , , , , , , , and methods perform operations on a sequence and return a single result. Some overloads of these methods throw an exception when the sequence is empty, while other overloads return `null`. The method also throws an exception when the sequence contains more than one element. +The , , , , , , , and methods perform operations on a sequence and return a single result. Some overloads of these methods throw an exception when the sequence is empty, while other overloads return `null`. The method also throws an exception when the sequence contains more than one element. > [!NOTE] > Most of the methods that throw an exception are overloads. Be sure that you understand the behavior of the overload that you choose. @@ -178,41 +178,41 @@ How you eliminate or handle the exception depends on your application's assumpti - When you deliberately call one of these methods without checking for an empty sequence, you are assuming that the sequence is not empty, and that an empty sequence is an unexpected occurrence. In this case, catching or rethrowing the exception is appropriate. -- If your failure to check for an empty sequence was inadvertent, you can call one of the overloads of the overload to determine whether a sequence contains any elements. +- If your failure to check for an empty sequence was inadvertent, you can call one of the overloads of the overload to determine whether a sequence contains any elements. > [!TIP] - > Calling the method before generating a sequence can improve performance if the data to be processed might contain a large number of elements or if operation that generates the sequence is expensive. + > Calling the method before generating a sequence can improve performance if the data to be processed might contain a large number of elements or if operation that generates the sequence is expensive. -- If you've called a method such as , , or , you can substitute an alternate method, such as , , or , that returns a default value instead of a member of the sequence. +- If you've called a method such as , , or , you can substitute an alternate method, such as , , or , that returns a default value instead of a member of the sequence. The examples provide additional detail. -The following example uses the method to compute the average of a sequence whose values are greater than 4. Since no values from the original array exceed 4, no values are included in the sequence, and the method throws an exception. +The following example uses the method to compute the average of a sequence whose values are greater than 4. Since no values from the original array exceed 4, no values are included in the sequence, and the method throws an exception. :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable1.cs" id="Snippet6"::: :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable1.fs" id="Snippet6"::: :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Enumerable1.vb" id="Snippet6"::: -The exception can be eliminated by calling the method to determine whether the sequence contains any elements before calling the method that processes the sequence, as the following example shows. +The exception can be eliminated by calling the method to determine whether the sequence contains any elements before calling the method that processes the sequence, as the following example shows. :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable2.cs" id="Snippet7"::: :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable2.fs" id="Snippet7"::: :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Enumerable2.vb" id="Snippet7"::: -The method returns the first item in a sequence or the first element in a sequence that satisfies a specified condition. If the sequence is empty and therefore does not have a first element, it throws an exception. +The method returns the first item in a sequence or the first element in a sequence that satisfies a specified condition. If the sequence is empty and therefore does not have a first element, it throws an exception. -In the following example, the method throws an exception because the dbQueryResults array doesn't contain an element greater than 4. +In the following example, the method throws an exception because the dbQueryResults array doesn't contain an element greater than 4. :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable3.cs" id="Snippet8"::: :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable3.fs" id="Snippet8"::: :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Enumerable3.vb" id="Snippet8"::: -You can call the method instead of to return a specified or default value. If the method does not find a first element in the sequence, it returns the default value for that data type. The default value is `null` for a reference type, zero for a numeric data type, and for the type. +You can call the method instead of to return a specified or default value. If the method does not find a first element in the sequence, it returns the default value for that data type. The default value is `null` for a reference type, zero for a numeric data type, and for the type. > [!NOTE] -> Interpreting the value returned by the method is often complicated by the fact that the default value of the type can be a valid value in the sequence. In this case, you an call the method to determine whether the sequence has valid members before calling the method. +> Interpreting the value returned by the method is often complicated by the fact that the default value of the type can be a valid value in the sequence. In this case, you an call the method to determine whether the sequence has valid members before calling the method. -The following example calls the method to prevent the exception thrown in the previous example. +The following example calls the method to prevent the exception thrown in the previous example. :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable4.cs" id="Snippet9"::: :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable4.fs" id="Snippet9"::: @@ -220,30 +220,30 @@ The following example calls the method returns the only element of a sequence, or the only element of a sequence that meets a specified condition. If there are no elements in the sequence, or if there is more than one element , the method throws an exception. +The method returns the only element of a sequence, or the only element of a sequence that meets a specified condition. If there are no elements in the sequence, or if there is more than one element , the method throws an exception. -You can use the method to return a default value instead of throwing an exception when the sequence contains no elements. However, the method still throws an exception when the sequence contains more than one element. +You can use the method to return a default value instead of throwing an exception when the sequence contains no elements. However, the method still throws an exception when the sequence contains more than one element. -The following table lists the exception messages from the exception objects thrown by calls to the and methods. +The following table lists the exception messages from the exception objects thrown by calls to the and methods. | Method | Message | |-----------------------------------|------------------------------------------------------| | `Single` | **Sequence contains no matching element** | | `Single`
`SingleOrDefault` | **Sequence contains more than one matching element** | -In the following example, the call to the method throws an exception because the sequence doesn't have an element greater than 4. +In the following example, the call to the method throws an exception because the sequence doesn't have an element greater than 4. :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable5.cs" id="Snippet10"::: :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable5.fs" id="Snippet10"::: :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Enumerable5.vb" id="Snippet10"::: -The following example attempts to prevent the exception thrown when a sequence is empty by instead calling the method. However, because this sequence returns multiple elements whose value is greater than 2, it also throws an exception. +The following example attempts to prevent the exception thrown when a sequence is empty by instead calling the method. However, because this sequence returns multiple elements whose value is greater than 2, it also throws an exception. :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable6.cs" id="Snippet11"::: :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable6.fs" id="Snippet11"::: :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Enumerable6.vb" id="Snippet11"::: -Calling the method assumes that either a sequence or the sequence that meets specified criteria contains only one element. assumes a sequence with zero or one result, but no more. If this assumption is a deliberate one on your part and these conditions are not met, rethrowing or catching the resulting is appropriate. Otherwise, or if you expect that invalid conditions will occur with some frequency, you should consider using some other method, such as or . +Calling the method assumes that either a sequence or the sequence that meets specified criteria contains only one element. assumes a sequence with zero or one result, but no more. If this assumption is a deliberate one on your part and these conditions are not met, rethrowing or catching the resulting is appropriate. Otherwise, or if you expect that invalid conditions will occur with some frequency, you should consider using some other method, such as or . ### Dynamic cross-application domain field access diff --git a/docs/fundamentals/runtime-libraries/system-io-filestream.md b/docs/fundamentals/runtime-libraries/system-io-filestream.md index 9aa84c664cc27..54e05646265f2 100644 --- a/docs/fundamentals/runtime-libraries/system-io-filestream.md +++ b/docs/fundamentals/runtime-libraries/system-io-filestream.md @@ -7,14 +7,14 @@ ms.date: 12/31/2023 [!INCLUDE [context](includes/context.md)] -Use the class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. You can use the , , , and methods to perform synchronous operations, or the , , , and methods to perform asynchronous operations. Use the asynchronous methods to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. buffers input and output for better performance. +Use the class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. You can use the , , , and methods to perform synchronous operations, or the , , , and methods to perform asynchronous operations. Use the asynchronous methods to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. buffers input and output for better performance. > [!IMPORTANT] -> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. +> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. -The property detects whether the file handle was opened asynchronously. You specify this value when you create an instance of the class using a constructor that has an `isAsync`, `useAsync`, or `options` parameter. When the property is `true`, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the property does not have to be `true` to call the , , or method. When the property is `false` and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously. +The property detects whether the file handle was opened asynchronously. You specify this value when you create an instance of the class using a constructor that has an `isAsync`, `useAsync`, or `options` parameter. When the property is `true`, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the property does not have to be `true` to call the , , or method. When the property is `false` and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously. -The method supports random access to files. allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three members of the enumeration. +The method supports random access to files. allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three members of the enumeration. > [!NOTE] > Disk files always support random access. At the time of construction, the property value is set to `true` or `false` depending on the underlying file type. If the underlying file type is FILE_TYPE_DISK, as defined in winbase.h, the property value is `true`. Otherwise, the property value is `false`. @@ -29,8 +29,8 @@ For a list of common file and directory operations, see [Common I/O Tasks](../.. When a object does not have an exclusive hold on its handle, another thread could access the file handle concurrently and change the position of the operating system's file pointer that is associated with the file handle. In this case, the cached position in the object and the cached data in the buffer could be compromised. The object routinely performs checks on methods that access the cached buffer to ensure that the operating system's handle position is the same as the cached position used by the object. -If an unexpected change in the handle position is detected in a call to the method, .NET discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream. +If an unexpected change in the handle position is detected in a call to the method, .NET discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream. -If an unexpected change in the handle position is detected in a call to the method, the contents of the buffer are discarded and an exception is thrown. +If an unexpected change in the handle position is detected in a call to the method, the contents of the buffer are discarded and an exception is thrown. A object will not have an exclusive hold on its handle when either the property is accessed to expose the handle or the object is given the property in its constructor. diff --git a/docs/fundamentals/runtime-libraries/system-io-filesystemwatcher.md b/docs/fundamentals/runtime-libraries/system-io-filesystemwatcher.md index 9d969c396e6df..f50607b7e9c4d 100644 --- a/docs/fundamentals/runtime-libraries/system-io-filesystemwatcher.md +++ b/docs/fundamentals/runtime-libraries/system-io-filesystemwatcher.md @@ -13,11 +13,11 @@ To watch for changes in all files, set the property to one of the values. For more information on the type of changes you can watch, see . -You can watch for renaming, deletion, or creation of files or directories. For example, to watch for renaming of text files, set the property to "*.txt" and call the method with a specified for its parameter. +You can watch for renaming, deletion, or creation of files or directories. For example, to watch for renaming of text files, set the property to "*.txt" and call the method with a specified for its parameter. -The Windows operating system notifies your component of file changes in a buffer created by the . If there are many changes in a short time, the buffer can overflow. This causes the component to lose track of changes in the directory, and it will only provide blanket notification. Increasing the size of the buffer with the property is expensive, as it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small yet large enough to not miss any file change events. To avoid a buffer overflow, use the and properties so you can filter out unwanted change notifications. +The Windows operating system notifies your component of file changes in a buffer created by the . If there are many changes in a short time, the buffer can overflow. This causes the component to lose track of changes in the directory, and it will only provide blanket notification. Increasing the size of the buffer with the property is expensive, as it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small yet large enough to not miss any file change events. To avoid a buffer overflow, use the and properties so you can filter out unwanted change notifications. -For a list of initial property values for an instance of , see the constructor. +For a list of initial property values for an instance of , see the constructor. Considerations when using the class: @@ -30,18 +30,18 @@ Considerations when using the class: The operating system and object interpret a cut-and-paste action or a move action as a rename action for a folder and its contents. If you cut and paste a folder with files into a folder being watched, the object reports only the folder as new, but not its contents because they are essentially only renamed. -To be notified that the contents of folders have been moved or copied into a watched folder, provide and event handler methods as suggested in the following table. +To be notified that the contents of folders have been moved or copied into a watched folder, provide and event handler methods as suggested in the following table. |Event Handler|Events Handled|Performs| |-------------------|--------------------|--------------| -||, , |Report changes in file attributes, created files, and deleted files.| -|||List the old and new paths of renamed files and folders, expanding recursively if needed.| +||, , |Report changes in file attributes, created files, and deleted files.| +|||List the old and new paths of renamed files and folders, expanding recursively if needed.| ## Events and buffer sizes Note that several factors can affect which file system change events are raised, as described by the following: -- Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several and some and events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by . +- Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several and some and events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by . - The can watch disks as long as they are not switched or removed. The does not raise events for CDs and DVDs, because time stamps and properties cannot change. Remote computers must have one of the required platforms installed for the component to function properly. Note that a may miss an event when the buffer size is exceeded. To avoid missing events, follow these guidelines: diff --git a/docs/fundamentals/runtime-libraries/system-linq-expressions-binaryexpression.md b/docs/fundamentals/runtime-libraries/system-linq-expressions-binaryexpression.md index b703e0d1f5d09..2a09ea7d544f3 100644 --- a/docs/fundamentals/runtime-libraries/system-linq-expressions-binaryexpression.md +++ b/docs/fundamentals/runtime-libraries/system-linq-expressions-binaryexpression.md @@ -15,59 +15,59 @@ The following tables summarize the factory methods that can be used to create a |Node Type|Factory Method| |---------------|--------------------| -||| -||| -||| -||| -||| -||| -||| -||| -||| +||| +||| +||| +||| +||| +||| +||| +||| +||| ## Bitwise operations |Node Type|Factory Method| |---------------|--------------------| -||| -||| -||| +||| +||| +||| ## Shift operations |Node Type|Factory Method| |---------------|--------------------| -||| -||| +||| +||| ## Conditional Boolean operations |Node Type|Factory Method| |---------------|--------------------| -||| -||| +||| +||| ## Comparison operations |Node Type|Factory Method| |---------------|--------------------| -||| -||| -||| -||| -||| -||| +||| +||| +||| +||| +||| +||| ## Coalescing operations |Node Type|Factory Method| |---------------|--------------------| -||| +||| ## Array indexing operations |Node Type|Factory Method| |---------------|--------------------| -||| +||| -In addition, the methods can also be used to create a . These factory methods can be used to create a of any node type that represents a binary operation. The parameter of these methods that is of type specifies the desired node type. +In addition, the methods can also be used to create a . These factory methods can be used to create a of any node type that represents a binary operation. The parameter of these methods that is of type specifies the desired node type. diff --git a/docs/fundamentals/runtime-libraries/system-linq-expressions-expression-add.md b/docs/fundamentals/runtime-libraries/system-linq-expressions-expression-add.md index 65565fcc8153e..1856b5edea920 100644 --- a/docs/fundamentals/runtime-libraries/system-linq-expressions-expression-add.md +++ b/docs/fundamentals/runtime-libraries/system-linq-expressions-expression-add.md @@ -7,7 +7,7 @@ ms.date: 01/24/2024 [!INCLUDE [context](includes/context.md)] -The method returns a that has the property set to the implementing method. The property is set to the type of the node. If the node is lifted, the and properties are both `true`. Otherwise, they are `false`. The property is `null`. +The method returns a that has the property set to the implementing method. The property is set to the type of the node. If the node is lifted, the and properties are both `true`. Otherwise, they are `false`. The property is `null`. The following information describes the implementing method, the node type, and whether a node is lifted. diff --git a/docs/fundamentals/runtime-libraries/system-midpointrounding.md b/docs/fundamentals/runtime-libraries/system-midpointrounding.md index 1953808b3c9ff..0abdea1f8a282 100644 --- a/docs/fundamentals/runtime-libraries/system-midpointrounding.md +++ b/docs/fundamentals/runtime-libraries/system-midpointrounding.md @@ -7,7 +7,7 @@ ms.date: 12/31/2023 [!INCLUDE [context](includes/context.md)] -Use the enumeration with appropriate overloads of , , and to provide more control of the rounding process. +Use the enumeration with appropriate overloads of , , and to provide more control of the rounding process. There are two overall rounding strategies—*round to nearest* and *directed rounding*—and each enumeration field participates in exactly one of these strategies. diff --git a/docs/fundamentals/runtime-libraries/system-net-ftpwebrequest-proxy.md b/docs/fundamentals/runtime-libraries/system-net-ftpwebrequest-proxy.md index f01f4a34d3e38..2987fdc57c629 100644 --- a/docs/fundamentals/runtime-libraries/system-net-ftpwebrequest-proxy.md +++ b/docs/fundamentals/runtime-libraries/system-net-ftpwebrequest-proxy.md @@ -10,9 +10,9 @@ ms.date: 01/24/2024 > [!NOTE] > This property is not supported on .NET Core, and setting it has no effect. Getting the property value returns `null`. -The property identifies the instance that communicates with the FTP server. The proxy is set by the system by using configuration files and the Local Area Network settings. To specify that no proxy should be used, set to the proxy instance returned by the method. For more information about automatic proxy detection, see [Automatic Proxy Detection](/dotnet/framework/network-programming/automatic-proxy-detection). +The property identifies the instance that communicates with the FTP server. The proxy is set by the system by using configuration files and the Local Area Network settings. To specify that no proxy should be used, set to the proxy instance returned by the method. For more information about automatic proxy detection, see [Automatic Proxy Detection](/dotnet/framework/network-programming/automatic-proxy-detection). -You must set before writing data to the request's stream or getting the response. Changing after calling the , , , or method causes an exception. +You must set before writing data to the request's stream or getting the response. Changing after calling the , , , or method causes an exception. The class supports HTTP and ISA Firewall Client proxies. diff --git a/docs/fundamentals/runtime-libraries/system-net-http-httpclient.md b/docs/fundamentals/runtime-libraries/system-net-http-httpclient.md index 2899bb71e86f7..38847f8b8502c 100644 --- a/docs/fundamentals/runtime-libraries/system-net-http-httpclient.md +++ b/docs/fundamentals/runtime-libraries/system-net-http-httpclient.md @@ -91,15 +91,15 @@ Disposing of the `HttpClient` instance closes the open connections and cancels a ## Buffering and request lifetime -By default, `HttpClient` methods (except ) buffer the responses from the server, reading all the response body into memory before returning the async result. Those requests will continue until one of the following occurs: +By default, `HttpClient` methods (except ) buffer the responses from the server, reading all the response body into memory before returning the async result. Those requests will continue until one of the following occurs: -- The succeeds and returns a result. -- The is reached, in which case the will be cancelled. +- The succeeds and returns a result. +- The is reached, in which case the will be cancelled. - The passable to some method overloads is fired. - is called. - The HttpClient is disposed. -You can change the buffering behavior on a per-request basis using the parameter available on some method overloads. This argument can be used to specify if the should be considered complete after reading just the response headers, or after reading and buffering the response content. +You can change the buffering behavior on a per-request basis using the parameter available on some method overloads. This argument can be used to specify if the should be considered complete after reading just the response headers, or after reading and buffering the response content. If your app that uses and related classes in the namespace intends to download large amounts of data (50 megabytes or more), then the app should stream those downloads and not use the default buffering. If you use the default buffering, the client memory usage will get very large, potentially resulting in substantially reduced performance. @@ -107,15 +107,15 @@ If your app that uses and related classes in t The following methods are thread safe: -- -- -- -- -- -- -- -- -- +- +- +- +- +- +- +- +- +- ## Proxies @@ -130,13 +130,13 @@ Proxy settings (like ) should be changed ## Timeouts -You can use to set a default timeout for all HTTP requests from the `HttpClient` instance. The timeout only applies to the xxxAsync methods that cause a request/response to be initiated. If the timeout is reached, the for that request is cancelled. +You can use to set a default timeout for all HTTP requests from the `HttpClient` instance. The timeout only applies to the xxxAsync methods that cause a request/response to be initiated. If the timeout is reached, the for that request is cancelled. You can set some additional timeouts if you pass in a instance when constructing the `HttpClient` object: | Property | Description | | ------------ | -------------- | -| | Specifies a timeout that's used when a request requires a new TCP connection to be created. If the timeout occurs, the request is cancelled. | +| | Specifies a timeout that's used when a request requires a new TCP connection to be created. If the timeout occurs, the request is cancelled. | | | Specifies a timeout to be used for each connection in the connection pool. If the connection is idle, the connection is immediately closed; otherwise, the connection is closed at the end of the current request. | | | If a connection in the connection pool is idle for this long, the connection is closed. | | | If request has an "Expect: 100-continue" header, it delays sending content until the timeout or until a "100-continue" response is received. | diff --git a/docs/fundamentals/runtime-libraries/system-net-httplistener.md b/docs/fundamentals/runtime-libraries/system-net-httplistener.md index 2f60075f63b65..603770fab1b32 100644 --- a/docs/fundamentals/runtime-libraries/system-net-httplistener.md +++ b/docs/fundamentals/runtime-libraries/system-net-httplistener.md @@ -15,20 +15,20 @@ A URI prefix string is composed of a scheme (http or https), a host, an optional When a port is specified, the host element can be replaced with "\*" to indicate that the accepts requests sent to the port if the requested URI does not match any other prefix. For example, to receive all requests sent to port 8080 when the requested URI is not handled by any , the prefix is *http://\*:8080/*. Similarly, to specify that the accepts all requests sent to a port, replace the host element with the "+" character. For example, *https://+:8080*. The "\*" and "+" characters can be present in prefixes that include paths. -Wildcard subdomains are supported in URI prefixes that are managed by an object. To specify a wildcard subdomain, use the "\*" character as part of the hostname in a URI prefix. For example, *http://\*.foo.com/*. Pass this as the argument to the method. +Wildcard subdomains are supported in URI prefixes that are managed by an object. To specify a wildcard subdomain, use the "\*" character as part of the hostname in a URI prefix. For example, *http://\*.foo.com/*. Pass this as the argument to the method. > [!WARNING] > Top-level wildcard bindings (*http://\*:8080/* and *http://+:8080*) should **not** be used. Top-level wildcard bindings can open up your app to security vulnerabilities. This applies to both strong and weak wildcards. Use explicit host names rather than wildcards. Subdomain wildcard binding (for example, `*.mysub.com`) doesn't have this security risk if you control the entire parent domain (as opposed to `*.com`, which is vulnerable). See [rfc7230 section-5.4](https://tools.ietf.org/html/rfc7230#section-5.4) for more information. -To begin listening for requests from clients, add the URI prefixes to the collection and call the method. offers both synchronous and asynchronous models for processing client requests. Requests and their associated responses are accessed using the object returned by the method or its asynchronous counterparts, the and methods. +To begin listening for requests from clients, add the URI prefixes to the collection and call the method. offers both synchronous and asynchronous models for processing client requests. Requests and their associated responses are accessed using the object returned by the method or its asynchronous counterparts, the and methods. -The synchronous model is appropriate if your application should block while waiting for a client request and if you want to process only one request at a time. Using the synchronous model, call the method, which waits for a client to send a request. The method returns an object to you for processing when one occurs. +The synchronous model is appropriate if your application should block while waiting for a client request and if you want to process only one request at a time. Using the synchronous model, call the method, which waits for a client to send a request. The method returns an object to you for processing when one occurs. -In the more complex asynchronous model, your application does not block while waiting for requests and each request is processed in its own execution thread. Use the method to specify an application-defined method to be called for each incoming request. Within that method, call the method to obtain the request, process it, and respond. +In the more complex asynchronous model, your application does not block while waiting for requests and each request is processed in its own execution thread. Use the method to specify an application-defined method to be called for each incoming request. Within that method, call the method to obtain the request, process it, and respond. In either model, incoming requests are accessed using the property and are represented by objects. Similarly, responses are accessed using the property and are represented by objects. These objects share some functionality with the and objects, but the latter objects cannot be used in conjunction with because they implement client, not server, behaviors. -An can require client authentication. You can either specify a particular scheme to use for authentication, or you can specify a delegate that determines the scheme to use. You must require some form of authentication to obtain information about the client's identity. For additional information, see the , , and properties. +An can require client authentication. You can either specify a particular scheme to use for authentication, or you can specify a delegate that determines the scheme to use. You must require some form of authentication to obtain information about the client's identity. For additional information, see the , , and properties. > [!NOTE] > If you create an using https, you must select a Server Certificate for that listener. Otherwise, requests to this will fail with an unexpected close of the connection. diff --git a/docs/fundamentals/runtime-libraries/system-net-sockets-socket.md b/docs/fundamentals/runtime-libraries/system-net-sockets-socket.md index 7bfe495819edc..8336cf59d819e 100644 --- a/docs/fundamentals/runtime-libraries/system-net-sockets-socket.md +++ b/docs/fundamentals/runtime-libraries/system-net-sockets-socket.md @@ -9,20 +9,20 @@ ms.date: 12/31/2023 The class provides a rich set of methods and properties for network communications. The class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the enumeration. -The class follows the .NET naming pattern for asynchronous methods. For example, the synchronous method corresponds to the asynchronous variants. +The class follows the .NET naming pattern for asynchronous methods. For example, the synchronous method corresponds to the asynchronous variants. Use the following methods for synchronous operation mode: -- If you are using a connection-oriented protocol such as TCP, your server can listen for connections using the method. The method processes any incoming connection requests and returns a that you can use to communicate data with the remote host. Use this returned to call the or method. Call the method prior to calling the method if you want to specify the local IP address and port number. Use a port number of zero if you want the underlying service provider to assign a free port for you. If you want to connect to a listening host, call the method. To communicate data, call the or method. -- If you are using a connectionless protocol such as UDP, you do not need to listen for connections at all. Call the method to accept any incoming datagrams. Use the method to send datagrams to a remote host. +- If you are using a connection-oriented protocol such as TCP, your server can listen for connections using the method. The method processes any incoming connection requests and returns a that you can use to communicate data with the remote host. Use this returned to call the or method. Call the method prior to calling the method if you want to specify the local IP address and port number. Use a port number of zero if you want the underlying service provider to assign a free port for you. If you want to connect to a listening host, call the method. To communicate data, call the or method. +- If you are using a connectionless protocol such as UDP, you do not need to listen for connections at all. Call the method to accept any incoming datagrams. Use the method to send datagrams to a remote host. To process communications asynchronously, use the following methods: -- If you are using a connection-oriented protocol such as TCP, use to connect with a listening host. Use or to communicate data asynchronously. Incoming connection requests can be processed using . -- If you are using a connectionless protocol such as UDP, you can use to send datagrams, and to receive datagrams. +- If you are using a connection-oriented protocol such as TCP, use to connect with a listening host. Use or to communicate data asynchronously. Incoming connection requests can be processed using . +- If you are using a connectionless protocol such as UDP, you can use to send datagrams, and to receive datagrams. If you perform multiple asynchronous operations on a socket, they do not necessarily complete in the order in which they are started. -When you are finished sending and receiving data, use the method to disable the . After calling , call the method to release all resources associated with the . +When you are finished sending and receiving data, use the method to disable the . After calling , call the method to release all resources associated with the . -The class allows you to configure your using the method. Retrieve these settings using the method. +The class allows you to configure your using the method. Retrieve these settings using the method. diff --git a/docs/fundamentals/runtime-libraries/system-notimplementedexception.md b/docs/fundamentals/runtime-libraries/system-notimplementedexception.md index 65c7c7c8118f6..1482a8bb1f7fd 100644 --- a/docs/fundamentals/runtime-libraries/system-notimplementedexception.md +++ b/docs/fundamentals/runtime-libraries/system-notimplementedexception.md @@ -9,7 +9,7 @@ ms.date: 12/31/2023 The exception is thrown when a particular method, get accessor, or set accessor is present as a member of a type but is not implemented. - uses the default implementation, which supports reference equality. For a list of initial values for an instance of , see the constructors. + uses the default implementation, which supports reference equality. For a list of initial values for an instance of , see the constructors. ## Throw the exception @@ -28,6 +28,6 @@ In some cases, a exception may not be used - Throw a exception on platforms on which the functionality is not supported if you've designed a type with one or more members that are available on some platforms or versions but not others. - Throw a exception if the implementation of an interface member or an override to an abstract base class method is not possible. - For example, the method throws a exception because no meaningful conversion between a date and time and a 32-bit signed integer exists. The method must be present in this case because the class implements the interface. + For example, the method throws a exception because no meaningful conversion between a date and time and a 32-bit signed integer exists. The method must be present in this case because the class implements the interface. You should also throw a exception if you've implemented an abstract base class and add a new member to it that must be overridden by derived classes. In that case, making the member abstract causes existing subclasses to fail to load. diff --git a/docs/fundamentals/runtime-libraries/system-notsupportedexception.md b/docs/fundamentals/runtime-libraries/system-notsupportedexception.md index f3b8d3bdfa505..0b92fee662638 100644 --- a/docs/fundamentals/runtime-libraries/system-notsupportedexception.md +++ b/docs/fundamentals/runtime-libraries/system-notsupportedexception.md @@ -15,7 +15,7 @@ dev_langs: uses the HRESULT `COR_E_NOTSUPPORTED`, which has the value 0x80131515. -For a list of initial property values for an instance of , see the constructors. +For a list of initial property values for an instance of , see the constructors. ## Throw a NotSupportedException exception @@ -33,12 +33,12 @@ You might consider throwing a exception in t ## Handle a NotSupportedException exception -The exception indicates that a method has no implementation and that you should not call it. You should not handle the exception. Instead, what you should do depends on the cause of the exception: whether an implementation is completely absent, or the member invocation is inconsistent with the purpose of an object (such as a call to the method on a read-only object). +The exception indicates that a method has no implementation and that you should not call it. You should not handle the exception. Instead, what you should do depends on the cause of the exception: whether an implementation is completely absent, or the member invocation is inconsistent with the purpose of an object (such as a call to the method on a read-only object). **An implementation has not been provided because the operation cannot be performed in a meaningful way.** This is a common exception when you are calling methods on an object that provides implementations for the methods of an abstract base class, or that implements a general-purpose interface, and the method has no meaningful implementation. -For example, the class implements the interface, which means that it must include a method to convert every primitive type to every other primitive type. Many of those conversions, however, are not possible. As a result, a call to the method, for instance, throws a exception because there is no possible conversion between a and a value +For example, the class implements the interface, which means that it must include a method to convert every primitive type to every other primitive type. Many of those conversions, however, are not possible. As a result, a call to the method, for instance, throws a exception because there is no possible conversion between a and a value To eliminate the exception, you should eliminate the method call. @@ -53,7 +53,7 @@ You're attempting to invoke a member whose functionality is unavailable because :::code language="fsharp" source="./snippets/System/NotSupportedException/Overview/fsharp/BadState1.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/NotSupportedException/Overview/vb/BadState1.vb" id="Snippet1"::: - Ycan eliminate the exception by ensuring that the instantiated object supports the functionality you intend. The following example addresses the problem of the read-only object by providing the correct arguments to the constructor. + Ycan eliminate the exception by ensuring that the instantiated object supports the functionality you intend. The following example addresses the problem of the read-only object by providing the correct arguments to the constructor. - You don't know the state of the object in advance, and the object doesn't support a particular operation. In most cases, the object should include a property or method that indicates whether it supports a particular set of operations. You can eliminate the exception by checking the value of the object and invoking the member only if appropriate. @@ -89,7 +89,7 @@ When working with the .NET Compact Framework and using P/Invoke on a native func - The .NET Compact Framework does not support what you are trying to do. - The DLL names are mangled on export. -If a exception is thrown, check: +If a exception is thrown, check: - For any violations of the .NET Compact Framework P/Invoke restrictions. - For any arguments that require pre-allocated memory. If these exist, you should pass a reference to an existing variable. diff --git a/docs/fundamentals/runtime-libraries/system-nullable.md b/docs/fundamentals/runtime-libraries/system-nullable.md index bf88004407f85..cdca18a5141bf 100644 --- a/docs/fundamentals/runtime-libraries/system-nullable.md +++ b/docs/fundamentals/runtime-libraries/system-nullable.md @@ -13,10 +13,10 @@ A type is said to be nullable if it can be assigned a value or can be assigned ` In C# and Visual Basic, you mark a value type as nullable by using the `?` notation after the value type. For example, `int?` in C# or `Integer?` in Visual Basic declares an integer value type that can be assigned `null`. -The class provides complementary support for the structure. The class supports obtaining the underlying type of a nullable type, and comparison and equality operations on pairs of nullable types whose underlying value type does not support generic comparison and equality operations. +The class provides complementary support for the structure. The class supports obtaining the underlying type of a nullable type, and comparison and equality operations on pairs of nullable types whose underlying value type does not support generic comparison and equality operations. ## Boxing and unboxing -When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the object, not the object itself. That is, if the property is `true`, the contents of the property is boxed. +When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the object, not the object itself. That is, if the property is `true`, the contents of the property is boxed. -If the `HasValue` property of a nullable type is `false`, the result of the boxing operation is `null`. When the underlying value of a nullable type is unboxed, the common language runtime creates a new structure initialized to the underlying value. +If the `HasValue` property of a nullable type is `false`, the result of the boxing operation is `null`. When the underlying value of a nullable type is unboxed, the common language runtime creates a new structure initialized to the underlying value. diff --git a/docs/fundamentals/runtime-libraries/system-nullable{t}.md b/docs/fundamentals/runtime-libraries/system-nullable{t}.md index ef632b0eee058..e2ab86e33b5de 100644 --- a/docs/fundamentals/runtime-libraries/system-nullable{t}.md +++ b/docs/fundamentals/runtime-libraries/system-nullable{t}.md @@ -13,20 +13,20 @@ A type is said to be nullable if it can be assigned a value or can be assigned ` In C# and Visual Basic, you mark a value type as nullable by using the `?` notation after the value type. For example, `int?` in C# or `Integer?` in Visual Basic declares an integer value type that can be assigned `null`. -The structure supports using only a value type as a nullable type because reference types are nullable by design. +The structure supports using only a value type as a nullable type because reference types are nullable by design. -The class provides complementary support for the structure. The class supports obtaining the underlying type of a nullable type, and comparison and equality operations on pairs of nullable types whose underlying value type does not support generic comparison and equality operations. +The class provides complementary support for the structure. The class supports obtaining the underlying type of a nullable type, and comparison and equality operations on pairs of nullable types whose underlying value type does not support generic comparison and equality operations. ## Fundamental properties -The two fundamental members of the structure are the and properties. If the property for a object is `true`, the value of the object can be accessed with the property. If the property is `false`, the value of the object is undefined and an attempt to access the property throws an . +The two fundamental members of the structure are the and properties. If the property for a object is `true`, the value of the object can be accessed with the property. If the property is `false`, the value of the object is undefined and an attempt to access the property throws an . ## Boxing and unboxing -When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the object, not the object itself. That is, if the property is `true`, the contents of the property is boxed. When the underlying value of a nullable type is unboxed, the common language runtime creates a new structure initialized to the underlying value. +When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the object, not the object itself. That is, if the property is `true`, the contents of the property is boxed. When the underlying value of a nullable type is unboxed, the common language runtime creates a new structure initialized to the underlying value. -If the `HasValue` property of a nullable type is `false`, the result of a boxing operation is `null`. Consequently, if a boxed nullable type is passed to a method that expects an object argument, that method must be prepared to handle the case where the argument is `null`. When `null` is unboxed into a nullable type, the common language runtime creates a new structure and initializes its `HasValue` property to `false`. +If the `HasValue` property of a nullable type is `false`, the result of a boxing operation is `null`. Consequently, if a boxed nullable type is passed to a method that expects an object argument, that method must be prepared to handle the case where the argument is `null`. When `null` is unboxed into a nullable type, the common language runtime creates a new structure and initializes its `HasValue` property to `false`. ## Windows runtime components -You can include a type as a member of a structure exported in a WinMD library. +You can include a type as a member of a structure exported in a WinMD library. diff --git a/docs/fundamentals/runtime-libraries/system-numerics-biginteger.md b/docs/fundamentals/runtime-libraries/system-numerics-biginteger.md index c46558cc360b4..39f5eadfaabc1 100644 --- a/docs/fundamentals/runtime-libraries/system-numerics-biginteger.md +++ b/docs/fundamentals/runtime-libraries/system-numerics-biginteger.md @@ -36,12 +36,12 @@ You can instantiate a object in several ways: These methods enable you to instantiate a object whose value is in the range of one of the existing numeric types only. You can instantiate a object whose value can exceed the range of the existing numeric types in one of three ways: -- You can use the `new` keyword and provide a byte array of any size to the constructor. For example: +- You can use the `new` keyword and provide a byte array of any size to the constructor. For example: :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs" id="Snippet4"::: :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/BigInteger_Examples.vb" id="Snippet4"::: -- You can call the or methods to convert the string representation of a number to a . For example: +- You can call the or methods to convert the string representation of a number to a . For example: :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs" id="Snippet5"::: :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/BigInteger_Examples.vb" id="Snippet5"::: @@ -51,21 +51,21 @@ These methods enable you to instantiate a obje :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs" id="Snippet6"::: :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/BigInteger_Examples.vb" id="Snippet6"::: -The uninitialized value of a is . +The uninitialized value of a is . ## Perform operations on BigInteger values -You can use a instance as you would use any other integral type. overloads the standard numeric operators to enable you to perform basic mathematical operations such as addition, subtraction, division, multiplication, and unary negation. You can also use the standard numeric operators to compare two values with each other. Like the other integral types, also supports the bitwise `And`, `Or`, `XOr`, left shift, and right shift operators. For languages that do not support custom operators, the structure also provides equivalent methods for performing mathematical operations. These include , , , , , and several others. +You can use a instance as you would use any other integral type. overloads the standard numeric operators to enable you to perform basic mathematical operations such as addition, subtraction, division, multiplication, and unary negation. You can also use the standard numeric operators to compare two values with each other. Like the other integral types, also supports the bitwise `And`, `Or`, `XOr`, left shift, and right shift operators. For languages that do not support custom operators, the structure also provides equivalent methods for performing mathematical operations. These include , , , , , and several others. Many members of the structure correspond directly to members of the other integral types. In addition, adds members such as the following: -- , which returns a value that indicates the sign of a value. +- , which returns a value that indicates the sign of a value. -- , which returns the absolute value of a value. +- , which returns the absolute value of a value. -- , which returns both the quotient and remainder of a division operation. +- , which returns both the quotient and remainder of a division operation. -- , which returns the greatest common divisor of two values. +- , which returns the greatest common divisor of two values. Many of these additional members correspond to the members of the class, which provides the functionality to work with the primitive numeric types. @@ -93,34 +93,34 @@ In such a case, you can improve performance by performing all intermediate assig ## Byte arrays and hexadecimal strings -If you convert values to byte arrays, or if you convert byte arrays to values, you must consider the order of bytes. The structure expects the individual bytes in a byte array to appear in little-endian order (that is, the lower-order bytes of the value precede the higher-order bytes). You can round-trip a value by calling the method and then passing the resulting byte array to the constructor, as the following example shows. +If you convert values to byte arrays, or if you convert byte arrays to values, you must consider the order of bytes. The structure expects the individual bytes in a byte array to appear in little-endian order (that is, the lower-order bytes of the value precede the higher-order bytes). You can round-trip a value by calling the method and then passing the resulting byte array to the constructor, as the following example shows. :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples.vb" id="Snippet1"::: -To instantiate a value from a byte array that represents a value of some other integral type, you can pass the integral value to the method, and then pass the resulting byte array to the constructor. The following example instantiates a value from a byte array that represents an value. +To instantiate a value from a byte array that represents a value of some other integral type, you can pass the integral value to the method, and then pass the resulting byte array to the constructor. The following example instantiates a value from a byte array that represents an value. :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs" id="Snippet2"::: :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples.vb" id="Snippet2"::: -The structure assumes that negative values are stored by using two's complement representation. Because the structure represents a numeric value with no fixed length, the constructor always interprets the most significant bit of the last byte in the array as a sign bit. To prevent the constructor from confusing the two's complement representation of a negative value with the sign and magnitude representation of a positive value, positive values in which the most significant bit of the last byte in the byte array would ordinarily be set should include an additional byte whose value is 0. For example, 0xC0 0xBD 0xF0 0xFF is the little-endian hexadecimal representation of either -1,000,000 or 4,293,967,296. Because the most significant bit of the last byte in this array is on, the value of the byte array would be interpreted by the constructor as -1,000,000. To instantiate a whose value is positive, a byte array whose elements are 0xC0 0xBD 0xF0 0xFF 0x00 must be passed to the constructor. The following example illustrates this. +The structure assumes that negative values are stored by using two's complement representation. Because the structure represents a numeric value with no fixed length, the constructor always interprets the most significant bit of the last byte in the array as a sign bit. To prevent the constructor from confusing the two's complement representation of a negative value with the sign and magnitude representation of a positive value, positive values in which the most significant bit of the last byte in the byte array would ordinarily be set should include an additional byte whose value is 0. For example, 0xC0 0xBD 0xF0 0xFF is the little-endian hexadecimal representation of either -1,000,000 or 4,293,967,296. Because the most significant bit of the last byte in this array is on, the value of the byte array would be interpreted by the constructor as -1,000,000. To instantiate a whose value is positive, a byte array whose elements are 0xC0 0xBD 0xF0 0xFF 0x00 must be passed to the constructor. The following example illustrates this. :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs" id="Snippet3"::: :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples.vb" id="Snippet3"::: -Byte arrays created by the method from positive values include this extra zero-value byte. Therefore, the structure can successfully round-trip values by assigning them to, and then restoring them from, byte arrays, as the following example shows. +Byte arrays created by the method from positive values include this extra zero-value byte. Therefore, the structure can successfully round-trip values by assigning them to, and then restoring them from, byte arrays, as the following example shows. :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs" id="Snippet4"::: :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples.vb" id="Snippet4"::: -However, you may need to add this additional zero-value byte to byte arrays that are created dynamically by the developer or that are returned by methods that convert unsigned integers to byte arrays (such as , , and ). +However, you may need to add this additional zero-value byte to byte arrays that are created dynamically by the developer or that are returned by methods that convert unsigned integers to byte arrays (such as , , and ). -When parsing a hexadecimal string, the and methods assume that if the most significant bit of the first byte in the string is set, or if the first hexadecimal digit of the string represents the lower four bits of a byte value, the value is represented by using two's complement representation. For example, both "FF01" and "F01" represent the decimal value -255. To differentiate positive from negative values, positive values should include a leading zero. The relevant overloads of the method, when they are passed the "X" format string, add a leading zero to the returned hexadecimal string for positive values. This makes it possible to round-trip values by using the and methods, as the following example shows. +When parsing a hexadecimal string, the and methods assume that if the most significant bit of the first byte in the string is set, or if the first hexadecimal digit of the string represents the lower four bits of a byte value, the value is represented by using two's complement representation. For example, both "FF01" and "F01" represent the decimal value -255. To differentiate positive from negative values, positive values should include a leading zero. The relevant overloads of the method, when they are passed the "X" format string, add a leading zero to the returned hexadecimal string for positive values. This makes it possible to round-trip values by using the and methods, as the following example shows. :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs" id="Snippet5"::: :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples.vb" id="Snippet5"::: -However, the hexadecimal strings created by calling the `ToString` methods of the other integral types or the overloads of the method that include a `toBase` parameter do not indicate the sign of the value or the source data type from which the hexadecimal string was derived. Successfully instantiating a value from such a string requires some additional logic. The following example provides one possible implementation. +However, the hexadecimal strings created by calling the `ToString` methods of the other integral types or the overloads of the method that include a `toBase` parameter do not indicate the sign of the value or the source data type from which the hexadecimal string was derived. Successfully instantiating a value from such a string requires some additional logic. The following example provides one possible implementation. :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples2.cs" id="Snippet6"::: :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples2.vb" id="Snippet6"::: diff --git a/docs/fundamentals/runtime-libraries/system-numerics-complex.md b/docs/fundamentals/runtime-libraries/system-numerics-complex.md index 61268bd7c3c1c..e4fd27767f6e4 100644 --- a/docs/fundamentals/runtime-libraries/system-numerics-complex.md +++ b/docs/fundamentals/runtime-libraries/system-numerics-complex.md @@ -25,13 +25,13 @@ You can assign a value to a complex number in one of the following ways: - By passing two values to its constructor. The first value represents the real part of the complex number, and the second value represents its imaginary part. These values represent the position of the complex number in the two-dimensional Cartesian coordinate system. -- By calling the static (`Shared` in Visual Basic) method to create a complex number from its polar coordinates. +- By calling the static (`Shared` in Visual Basic) method to create a complex number from its polar coordinates. - By assigning a , , , , , , , , , or value to a object. The value becomes the real part of the complex number, and its imaginary part equals 0. - By casting (in C#) or converting (in Visual Basic) a or value to a object. The value becomes the real part of the complex number, and its imaginary part equals 0. -- By assigning the complex number that is returned by a method or operator to a object. For example, is a static method that returns a complex number that is the sum of two complex numbers, and the operator adds two complex numbers and returns the result. +- By assigning the complex number that is returned by a method or operator to a object. For example, is a static method that returns a complex number that is the sum of two complex numbers, and the operator adds two complex numbers and returns the result. The following example demonstrates each of these five ways of assigning a value to a complex number. @@ -47,7 +47,7 @@ The structure in .NET includes members that provi - Methods to perform other numerical operations on complex numbers. In addition to the four basic arithmetic operations, you can raise a complex number to a specified power, find the square root of a complex number, and get the absolute value of a complex number. - Methods to perform trigonometric operations on complex numbers. For example, you can calculate the tangent of an angle represented by a complex number. -Note that, because the and properties are read-only, you cannot modify the value of an existing object. All methods that perform an operation on a number, if their return value is of type , return a new number. +Note that, because the and properties are read-only, you cannot modify the value of an existing object. All methods that perform an operation on a number, if their return value is of type , return a new number. ## Precision and complex numbers @@ -85,9 +85,9 @@ Note that this applies to any intermediate calculations performed by a method. F ## Format a complex number -By default, the string representation of a complex number takes the form `<`*real*`;` *imaginary*`>`, where *real* and *imaginary* are the string representations of the values that form the complex number's real and imaginary components. Some overloads of the method allow customization of the string representations of these values to reflect the formatting conventions of a particular culture or to appear in a particular format defined by a standard or custom numeric format string. (For more information, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md).) +By default, the string representation of a complex number takes the form `<`*real*`;` *imaginary*`>`, where *real* and *imaginary* are the string representations of the values that form the complex number's real and imaginary components. Some overloads of the method allow customization of the string representations of these values to reflect the formatting conventions of a particular culture or to appear in a particular format defined by a standard or custom numeric format string. (For more information, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md).) -One of the more common ways of expressing the string representation of a complex number takes the form `a + bi`, where `a` is the complex number's real component, and `b` is the complex number's imaginary component. In electrical engineering, a complex number is most commonly expressed as `a + bj`. You can return the string representation of a complex number in either of these two forms. To do this, define a custom format provider by implementing the and interfaces, and then call the method. +One of the more common ways of expressing the string representation of a complex number takes the form `a + bi`, where `a` is the complex number's real component, and `b` is the complex number's imaginary component. In electrical engineering, a complex number is most commonly expressed as `a + bj`. You can return the string representation of a complex number in either of these two forms. To do this, define a custom format provider by implementing the and interfaces, and then call the method. The following example defines a `ComplexFormatter` class that represents a complex number as a string in the form of either `a + bi` or `a + bj`. diff --git a/docs/fundamentals/runtime-libraries/system-object-equals.md b/docs/fundamentals/runtime-libraries/system-object-equals.md index 7f0fdca13a2f9..40ec1e8eae486 100644 --- a/docs/fundamentals/runtime-libraries/system-object-equals.md +++ b/docs/fundamentals/runtime-libraries/system-object-equals.md @@ -15,7 +15,7 @@ This article pertains to the method tests for reference equality, and a call to the method is equivalent to a call to the method. Reference equality means that the object variables that are compared refer to the same object. The following example illustrates the result of such a comparison. It defines a `Person` class, which is a reference type, and calls the `Person` class constructor to instantiate two new `Person` objects, `person1a` and `person2`, which have the same value. It also assigns `person1a` to another object variable, `person1b`. As the output from the example shows, `person1a` and `person1b` are equal because they reference the same object. However, `person1a` and `person2` are not equal, although they have the same value. +- If the current instance is a reference type, the method tests for reference equality, and a call to the method is equivalent to a call to the method. Reference equality means that the object variables that are compared refer to the same object. The following example illustrates the result of such a comparison. It defines a `Person` class, which is a reference type, and calls the `Person` class constructor to instantiate two new `Person` objects, `person1a` and `person2`, which have the same value. It also assigns `person1a` to another object variable, `person1b`. As the output from the example shows, `person1a` and `person1b` are equal because they reference the same object. However, `person1a` and `person2` are not equal, although they have the same value. :::code language="csharp" source="./snippets/System/Object/Equals/csharp/equals_ref.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals_ref.fs" id="Snippet2"::: @@ -35,18 +35,18 @@ The type of comparison between the current instance and the `obj` parameter depe :::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals_val2.fs" id="Snippet4"::: :::code language="vb" source="./snippets/System/Object/Equals/vb/equals_val2.vb" id="Snippet4"::: -Because the class is the base class for all types in .NET, the method provides the default equality comparison for all other types. However, types often override the method to implement value equality. For more information, see the Notes for Callers and Notes for Inheritors sections. +Because the class is the base class for all types in .NET, the method provides the default equality comparison for all other types. However, types often override the method to implement value equality. For more information, see the Notes for Callers and Notes for Inheritors sections. ## Notes for the Windows Runtime -When you call the method overload on a class in the Windows Runtime, it provides the default behavior for classes that don't override . This is part of the support that .NET provides for the Windows Runtime (see [.NET Support for Windows Store Apps and Windows Runtime](/dotnet/standard/cross-platform/support-for-windows-store-apps-and-windows-runtime)). Classes in the Windows Runtime don't inherit , and currently don't implement an method. However, they appear to have , , and methods when you use them in your C# or Visual Basic code, and .NET provides the default behavior for these methods. +When you call the method overload on a class in the Windows Runtime, it provides the default behavior for classes that don't override . This is part of the support that .NET provides for the Windows Runtime (see [.NET Support for Windows Store Apps and Windows Runtime](/dotnet/standard/cross-platform/support-for-windows-store-apps-and-windows-runtime)). Classes in the Windows Runtime don't inherit , and currently don't implement an method. However, they appear to have , , and methods when you use them in your C# or Visual Basic code, and .NET provides the default behavior for these methods. > [!NOTE] > Windows Runtime classes that are written in C# or Visual Basic can override the method overload. ## Notes for callers -Derived classes frequently override the method to implement value equality. In addition, types also frequently provide an additional strongly typed overload to the `Equals` method, typically by implementing the interface. When you call the `Equals` method to test for equality, you should know whether the current instance overrides and understand how a particular call to an `Equals` method is resolved. Otherwise, you may be performing a test for equality that is different from what you intended, and the method may return an unexpected value. +Derived classes frequently override the method to implement value equality. In addition, types also frequently provide an additional strongly typed overload to the `Equals` method, typically by implementing the interface. When you call the `Equals` method to test for equality, you should know whether the current instance overrides and understand how a particular call to an `Equals` method is resolved. Otherwise, you may be performing a test for equality that is different from what you intended, and the method may return an unexpected value. The following example provides an illustration. It instantiates three objects with identical strings, and then makes four calls to `Equals` methods. The first method call returns `true`, and the remaining three return `false`. @@ -54,9 +54,9 @@ The following example provides an illustration. It instantiates three method overload, which tests for value equality, is called. Because the strings assigned to the two objects are equal, the method returns `true`. However, does not override . Because of this, when the object is cast to an , when a instance is assigned to a variable of type , and when the method is passed two objects, the default method is called. Because is a reference type, this is equivalent to passing the two objects to the method. Although all three objects contain identical strings, they refer to three distinct objects. As a result, these three method calls return `false`. +In the first case, the strongly typed method overload, which tests for value equality, is called. Because the strings assigned to the two objects are equal, the method returns `true`. However, does not override . Because of this, when the object is cast to an , when a instance is assigned to a variable of type , and when the method is passed two objects, the default method is called. Because is a reference type, this is equivalent to passing the two objects to the method. Although all three objects contain identical strings, they refer to three distinct objects. As a result, these three method calls return `false`. -You can compare the current object to another object for reference equality by calling the method. In Visual Basic, you can also use the `is` keyword (for example, `If Me Is otherObject Then ...`). +You can compare the current object to another object for reference equality by calling the method. In Visual Basic, you can also use the `is` keyword (for example, `If Me Is otherObject Then ...`). ## Notes for inheritors @@ -64,21 +64,21 @@ When you define your own type, that type inherits the functionality defined by t |Type category|Equality defined by|Comments| |-------------------|-------------------------|--------------| -|Class derived directly from ||Reference equality; equivalent to calling .| -|Structure||Value equality; either direct byte-by-byte comparison or field-by-field comparison using reflection.| -|Enumeration||Values must have the same enumeration type and the same underlying value.| -|Delegate||Delegates must have the same type with identical invocation lists.| +|Class derived directly from ||Reference equality; equivalent to calling .| +|Structure||Value equality; either direct byte-by-byte comparison or field-by-field comparison using reflection.| +|Enumeration||Values must have the same enumeration type and the same underlying value.| +|Delegate||Delegates must have the same type with identical invocation lists.| |Interface||Reference equality.| -For a value type, you should always override , because tests for equality that rely on reflection offer poor performance. You can also override the default implementation of for reference types to test for value equality instead of reference equality and to define the precise meaning of value equality. Such implementations of return `true` if the two objects have the same value, even if they are not the same instance. The type's implementer decides what constitutes an object's value, but it is typically some or all the data stored in the instance variables of the object. For example, the value of a object is based on the characters of the string; the method overrides the method to return `true` for any two string instances that contain the same characters in the same order. +For a value type, you should always override , because tests for equality that rely on reflection offer poor performance. You can also override the default implementation of for reference types to test for value equality instead of reference equality and to define the precise meaning of value equality. Such implementations of return `true` if the two objects have the same value, even if they are not the same instance. The type's implementer decides what constitutes an object's value, but it is typically some or all the data stored in the instance variables of the object. For example, the value of a object is based on the characters of the string; the method overrides the method to return `true` for any two string instances that contain the same characters in the same order. -The following example shows how to override the method to test for value equality. It overrides the method for the `Person` class. If `Person` accepted its base class implementation of equality, two `Person` objects would be equal only if they referenced a single object. However, in this case, two `Person` objects are equal if they have the same value for the `Person.Id` property. +The following example shows how to override the method to test for value equality. It overrides the method for the `Person` class. If `Person` accepted its base class implementation of equality, two `Person` objects would be equal only if they referenced a single object. However, in this case, two `Person` objects are equal if they have the same value for the `Person.Id` property. :::code language="csharp" source="./snippets/System/Object/Equals/csharp/equalsoverride.cs" id="Snippet6"::: :::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equalsoverride.fs" id="Snippet6"::: :::code language="vb" source="./snippets/System/Object/Equals/vb/equalsoverride.vb" id="Snippet6"::: -In addition to overriding , you can implement the interface to provide a strongly typed test for equality. +In addition to overriding , you can implement the interface to provide a strongly typed test for equality. The following statements must be true for all implementations of the method. In the list, `x`, `y`, and `z` represent object references that are not **null**. @@ -94,27 +94,27 @@ The following statements must be true for all implementations of the must not throw exceptions; they should always return a value. For example, if `obj` is `null`, the method should return `false` instead of throwing an . +Implementations of must not throw exceptions; they should always return a value. For example, if `obj` is `null`, the method should return `false` instead of throwing an . Follow these guidelines when overriding : - Types that implement must override . -- Types that override must also override ; otherwise, hash tables might not work correctly. +- Types that override must also override ; otherwise, hash tables might not work correctly. -- You should consider implementing the interface to support strongly typed tests for equality. Your implementation should return results that are consistent with . +- You should consider implementing the interface to support strongly typed tests for equality. Your implementation should return results that are consistent with . -- If your programming language supports operator overloading and you overload the equality operator for a given type, you must also override the method to return the same result as the equality operator. This helps ensure that class library code that uses (such as and ) behaves in a manner that is consistent with the way the equality operator is used by application code. +- If your programming language supports operator overloading and you overload the equality operator for a given type, you must also override the method to return the same result as the equality operator. This helps ensure that class library code that uses (such as and ) behaves in a manner that is consistent with the way the equality operator is used by application code. ### Guidelines for reference types The following guidelines apply to overriding for a reference type: -- Consider overriding if the semantics of the type are based on the fact that the type represents some value(s). +- Consider overriding if the semantics of the type are based on the fact that the type represents some value(s). -- Most reference types must not overload the equality operator, even if they override . However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you must override the equality operator. +- Most reference types must not overload the equality operator, even if they override . However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you must override the equality operator. -- You should not override on a mutable reference type. This is because overriding requires that you also override the method, as discussed in the previous section. This means that the hash code of an instance of a mutable reference type can change during its lifetime, which can cause the object to be lost in a hash table. +- You should not override on a mutable reference type. This is because overriding requires that you also override the method, as discussed in the previous section. This means that the hash code of an instance of a mutable reference type can change during its lifetime, which can cause the object to be lost in a hash table. ### Guidelines for value types @@ -122,13 +122,13 @@ The following guidelines apply to overriding . The implementation provided by performs a byte-by-byte comparison for value types whose fields are all value types, but it uses reflection to perform a field-by-field comparison of value types whose fields include reference types. -- If you override and your development language supports operator overloading, you must overload the equality operator. +- If you override and your development language supports operator overloading, you must overload the equality operator. -- You should implement the interface. Calling the strongly typed method avoids boxing the `obj` argument. +- You should implement the interface. Calling the strongly typed method avoids boxing the `obj` argument. ## Examples -The following example shows a `Point` class that overrides the method to provide value equality, and a `Point3D` class that is derived from `Point`. Because `Point` overrides to test for value equality, the method is not called. However, `Point3D.Equals` calls `Point.Equals` because `Point` implements in a manner that provides value equality. +The following example shows a `Point` class that overrides the method to provide value equality, and a `Point3D` class that is derived from `Point`. Because `Point` overrides to test for value equality, the method is not called. However, `Point3D.Equals` calls `Point.Equals` because `Point` implements in a manner that provides value equality. :::code language="csharp" source="./snippets/System/Object/Equals/csharp/equals2.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals2.fs" id="Snippet1"::: @@ -136,9 +136,9 @@ The following example shows a `Point` class that overrides the method to determine whether the runtime types of the two objects are identical. If the method used a check of the form `obj is Point` in C# or `TryCast(obj, Point)` in Visual Basic, the check would return `true` in cases where `obj` is an instance of a derived class of `Point`, even though `obj` and the current instance are not of the same runtime type. Having verified that both objects are of the same type, the method casts `obj` to type `Point` and returns the result of comparing the instance fields of the two objects. +The `Point.Equals` method calls the method to determine whether the runtime types of the two objects are identical. If the method used a check of the form `obj is Point` in C# or `TryCast(obj, Point)` in Visual Basic, the check would return `true` in cases where `obj` is an instance of a derived class of `Point`, even though `obj` and the current instance are not of the same runtime type. Having verified that both objects are of the same type, the method casts `obj` to type `Point` and returns the result of comparing the instance fields of the two objects. -In `Point3D.Equals`, the inherited `Point.Equals` method, which overrides , is invoked before anything else is done. Because `Point3D` is a sealed class (`NotInheritable` in Visual Basic), a check in the form `obj is Point` in C# or `TryCast(obj, Point)` in Visual Basic is adequate to ensure that `obj` is a `Point3D` object. If it is a `Point3D` object, it is cast to a `Point` object and passed to the base class implementation of . Only when the inherited `Point.Equals` method returns `true` does the method compare the `z` instance fields introduced in the derived class. +In `Point3D.Equals`, the inherited `Point.Equals` method, which overrides , is invoked before anything else is done. Because `Point3D` is a sealed class (`NotInheritable` in Visual Basic), a check in the form `obj is Point` in C# or `TryCast(obj, Point)` in Visual Basic is adequate to ensure that `obj` is a `Point3D` object. If it is a `Point3D` object, it is cast to a `Point` object and passed to the base class implementation of . Only when the inherited `Point.Equals` method returns `true` does the method compare the `z` instance fields introduced in the derived class. The following example defines a `Rectangle` class that internally implements a rectangle as two `Point` objects. The `Rectangle` class also overrides to provide for value equality. @@ -152,4 +152,4 @@ Some languages such as C# and Visual Basic support operator overloading. When a :::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals4.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/Object/Equals/vb/equals4.vb" id="Snippet1"::: -Because `Complex` is a value type, it cannot be derived from. Therefore, the override to method need not call to determine the precise runtime type of each object, but can instead use the `is` operator in C# or the `TypeOf` operator in Visual Basic to check the type of the `obj` parameter. +Because `Complex` is a value type, it cannot be derived from. Therefore, the override to method need not call to determine the precise runtime type of each object, but can instead use the `is` operator in C# or the `TypeOf` operator in Visual Basic to check the type of the `obj` parameter. diff --git a/docs/fundamentals/runtime-libraries/system-object-finalize.md b/docs/fundamentals/runtime-libraries/system-object-finalize.md index 84a0e278fb570..c3f3d7dad0fe4 100644 --- a/docs/fundamentals/runtime-libraries/system-object-finalize.md +++ b/docs/fundamentals/runtime-libraries/system-object-finalize.md @@ -11,56 +11,56 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed. The method is protected and therefore is accessible only through this class or through a derived class. +The method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed. The method is protected and therefore is accessible only through this class or through a derived class. ## How finalization works -The class provides no implementation for the method, and the garbage collector does not mark types derived from for finalization unless they override the method. +The class provides no implementation for the method, and the garbage collector does not mark types derived from for finalization unless they override the method. -If a type does override the method, the garbage collector adds an entry for each instance of the type to an internal structure called the finalization queue. The finalization queue contains entries for all the objects in the managed heap whose finalization code must run before the garbage collector can reclaim their memory. The garbage collector then calls the method automatically under the following conditions: +If a type does override the method, the garbage collector adds an entry for each instance of the type to an internal structure called the finalization queue. The finalization queue contains entries for all the objects in the managed heap whose finalization code must run before the garbage collector can reclaim their memory. The garbage collector then calls the method automatically under the following conditions: -- After the garbage collector has discovered that an object is inaccessible, unless the object has been exempted from finalization by a call to the method. +- After the garbage collector has discovered that an object is inaccessible, unless the object has been exempted from finalization by a call to the method. - **On .NET Framework only**, during shutdown of an application domain, unless the object is exempt from finalization. During shutdown, even objects that are still accessible are finalized. - is automatically called only once on a given instance, unless the object is re-registered by using a mechanism such as and the method has not been subsequently called. + is automatically called only once on a given instance, unless the object is re-registered by using a mechanism such as and the method has not been subsequently called. - operations have the following limitations: + operations have the following limitations: -- The exact time when the finalizer executes is undefined. To ensure deterministic release of resources for instances of your class, implement a `Close` method or provide a implementation. +- The exact time when the finalizer executes is undefined. To ensure deterministic release of resources for instances of your class, implement a `Close` method or provide a implementation. - The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already been finalized when the finalizer of Object A starts. - The thread on which the finalizer runs is unspecified. -The method might not run to completion or might not run at all under the following exceptional circumstances: +The method might not run to completion or might not run at all under the following exceptional circumstances: - If another finalizer blocks indefinitely (goes into an infinite loop, tries to obtain a lock it can never obtain, and so on). Because the runtime tries to run finalizers to completion, other finalizers might not be called if a finalizer blocks indefinitely. - If the process terminates without giving the runtime a chance to clean up. In this case, the runtime's first notification of process termination is a DLL_PROCESS_DETACH notification. The runtime continues to finalize objects during shutdown only while the number of finalizable objects continues to decrease. -If or an override of throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active `try`/`finally` blocks or finalizers are executed. This behavior ensures process integrity if the finalizer cannot free or destroy resources. +If or an override of throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active `try`/`finally` blocks or finalizers are executed. This behavior ensures process integrity if the finalizer cannot free or destroy resources. ## Overriding the Finalize method -You should override for a class that uses unmanaged resources, such as file handles or database connections that must be released when the managed object that uses them is discarded during garbage collection. You shouldn't implement a method for managed objects because the garbage collector releases managed resources automatically. +You should override for a class that uses unmanaged resources, such as file handles or database connections that must be released when the managed object that uses them is discarded during garbage collection. You shouldn't implement a method for managed objects because the garbage collector releases managed resources automatically. > [!IMPORTANT] -> If a object is available that wraps your unmanaged resource, the recommended alternative is to implement the dispose pattern with a safe handle and not override . For more information, see [The SafeHandle alternative](#the-safehandle-alternative) section. +> If a object is available that wraps your unmanaged resource, the recommended alternative is to implement the dispose pattern with a safe handle and not override . For more information, see [The SafeHandle alternative](#the-safehandle-alternative) section. -The method does nothing by default, but you should override only if necessary, and only to release unmanaged resources. Reclaiming memory tends to take much longer if a finalization operation runs, because it requires at least two garbage collections. In addition, you should override the method for reference types only. The common language runtime only finalizes reference types. It ignores finalizers on value types. +The method does nothing by default, but you should override only if necessary, and only to release unmanaged resources. Reclaiming memory tends to take much longer if a finalization operation runs, because it requires at least two garbage collections. In addition, you should override the method for reference types only. The common language runtime only finalizes reference types. It ignores finalizers on value types. -The scope of the method is `protected`. You should maintain this limited scope when you override the method in your class. By keeping a method protected, you prevent users of your application from calling an object's method directly. +The scope of the method is `protected`. You should maintain this limited scope when you override the method in your class. By keeping a method protected, you prevent users of your application from calling an object's method directly. -Every implementation of in a derived type must call its base type's implementation of . This is the only case in which application code is allowed to call . An object's method shouldn't call a method on any objects other than that of its base class. This is because the other objects being called could be collected at the same time as the calling object, such as in the case of a common language runtime shutdown. +Every implementation of in a derived type must call its base type's implementation of . This is the only case in which application code is allowed to call . An object's method shouldn't call a method on any objects other than that of its base class. This is because the other objects being called could be collected at the same time as the calling object, such as in the case of a common language runtime shutdown. > [!NOTE] -> The C# compiler does not allow you to override the method. Instead, you provide a finalizer by implementing a [destructor](/dotnet/csharp/programming-guide/classes-and-structs/destructors) for your class. A C# destructor automatically calls the destructor of its base class. +> The C# compiler does not allow you to override the method. Instead, you provide a finalizer by implementing a [destructor](/dotnet/csharp/programming-guide/classes-and-structs/destructors) for your class. A C# destructor automatically calls the destructor of its base class. > -> Visual C++ also provides its own syntax for implementing the method. For more information, see the "Destructors and finalizers" section of [How to: Define and Consume Classes and Structs (C++/CLI)](/cpp/dotnet/how-to-define-and-consume-classes-and-structs-cpp-cli). +> Visual C++ also provides its own syntax for implementing the method. For more information, see the "Destructors and finalizers" section of [How to: Define and Consume Classes and Structs (C++/CLI)](/cpp/dotnet/how-to-define-and-consume-classes-and-structs-cpp-cli). Because garbage collection is non-deterministic, you do not know precisely when the garbage collector performs finalization. To release resources immediately, you can also choose to implement the [dispose pattern](../../standard/garbage-collection/implementing-dispose.md) -and the interface. The implementation can be called by consumers of your class to free unmanaged resources, and you can use the method to free unmanaged resources in the event that the method is not called. +and the interface. The implementation can be called by consumers of your class to free unmanaged resources, and you can use the method to free unmanaged resources in the event that the method is not called. - can take almost any action, including resurrecting an object (that is, making the object accessible again) after it has been cleaned up during garbage collection. However, the object can only be resurrected once; cannot be called on resurrected objects during garbage collection. + can take almost any action, including resurrecting an object (that is, making the object accessible again) after it has been cleaned up during garbage collection. However, the object can only be resurrected once; cannot be called on resurrected objects during garbage collection. ## The SafeHandle alternative @@ -74,7 +74,7 @@ Creating reliable finalizers is often difficult, because you cannot make assumpt - is a wrapper class for a handle to a registry key. - is a wrapper class for a wait handle. -The following example uses the [dispose pattern](../../standard/garbage-collection/implementing-dispose.md) with safe handles instead of overriding the method. It defines a `FileAssociation` class that wraps registry information about the application that handles files with a particular file extension. The two registry handles returned as `out` parameters by Windows [RegOpenKeyEx](/windows/win32/api/winreg/nf-winreg-regopenkeyexa) function calls are passed to the constructor. The type's protected `Dispose` method then calls the `SafeRegistryHandle.Dispose` method to free these two handles. +The following example uses the [dispose pattern](../../standard/garbage-collection/implementing-dispose.md) with safe handles instead of overriding the method. It defines a `FileAssociation` class that wraps registry information about the application that handles files with a particular file extension. The two registry handles returned as `out` parameters by Windows [RegOpenKeyEx](/windows/win32/api/winreg/nf-winreg-regopenkeyexa) function calls are passed to the constructor. The type's protected `Dispose` method then calls the `SafeRegistryHandle.Dispose` method to free these two handles. :::code language="csharp" source="./snippets/System/Object/Finalize/csharp/finalize_safe.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/Object/Finalize/fsharp/finalize_safe.fs" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-object-gethashcode.md b/docs/fundamentals/runtime-libraries/system-object-gethashcode.md index cdd636c02a399..76ca507b4427e 100644 --- a/docs/fundamentals/runtime-libraries/system-object-gethashcode.md +++ b/docs/fundamentals/runtime-libraries/system-object-gethashcode.md @@ -11,12 +11,12 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The method provides a hash code for algorithms that need quick checks of object equality. A hash code is a numeric value that is used to insert and identify an object in a hash-based collection, such as the class, the class, or a type derived from the class. +The method provides a hash code for algorithms that need quick checks of object equality. A hash code is a numeric value that is used to insert and identify an object in a hash-based collection, such as the class, the class, or a type derived from the class. > [!NOTE] > For information about how hash codes are used in hash tables and for some additional hash code algorithms, see the [Hash Function](https://en.wikipedia.org/wiki/Hash_function) entry in Wikipedia. -Two objects that are equal return hash codes that are equal. However, the reverse is not true: equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes. Furthermore, .NET does not guarantee the default implementation of the method, and the value this method returns may differ between .NET implementations, such as different versions of .NET Framework and .NET Core, and platforms, such as 32-bit and 64-bit platforms. For these reasons, do not use the default implementation of this method as a unique object identifier for hashing purposes. Two consequences follow from this: +Two objects that are equal return hash codes that are equal. However, the reverse is not true: equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes. Furthermore, .NET does not guarantee the default implementation of the method, and the value this method returns may differ between .NET implementations, such as different versions of .NET Framework and .NET Core, and platforms, such as 32-bit and 64-bit platforms. For these reasons, do not use the default implementation of this method as a unique object identifier for hashing purposes. Two consequences follow from this: - You should not assume that equal hash codes imply object equality. - You should never persist or use a hash code outside the application domain in which it was created, because the same object may hash across application domains, processes, and platforms. @@ -28,21 +28,21 @@ Two objects that are equal return hash codes that are equal. However, the revers > - Do not use the hash code as the key to retrieve an object from a keyed collection. > - Do not send hash codes across application domains or processes. In some cases, hash codes may be computed on a per-process or per-application domain basis. > - Do not use the hash code instead of a value returned by a cryptographic hashing function if you need a cryptographically strong hash. For cryptographic hashes, use a class derived from the or class. -> - Do not test for equality of hash codes to determine whether two objects are equal. (Unequal objects can have identical hash codes.) To test for equality, call the or method. +> - Do not test for equality of hash codes to determine whether two objects are equal. (Unequal objects can have identical hash codes.) To test for equality, call the or method. -The method can be overridden by a derived type. If is not overridden, hash codes for reference types are computed by calling the method of the base class, which computes a hash code based on an object's reference; for more information, see . In other words, two objects for which the method returns `true` have identical hash codes. If value types do not override , the method of the base class uses reflection to compute the hash code based on the values of the type's fields. In other words, value types whose fields have equal values have equal hash codes. For more information about overriding , see the "Notes to Inheritors" section. +The method can be overridden by a derived type. If is not overridden, hash codes for reference types are computed by calling the method of the base class, which computes a hash code based on an object's reference; for more information, see . In other words, two objects for which the method returns `true` have identical hash codes. If value types do not override , the method of the base class uses reflection to compute the hash code based on the values of the type's fields. In other words, value types whose fields have equal values have equal hash codes. For more information about overriding , see the "Notes to Inheritors" section. > [!WARNING] -> If you override the method, you should also override , and vice versa. If your overridden method returns `true` when two objects are tested for equality, your overridden method must return the same value for the two objects. +> If you override the method, you should also override , and vice versa. If your overridden method returns `true` when two objects are tested for equality, your overridden method must return the same value for the two objects. -If an object that is used as a key in a hash table does not provide a useful implementation of , you can specify a hash code provider by supplying an implementation to one of the overloads of the class constructor. +If an object that is used as a key in a hash table does not provide a useful implementation of , you can specify a hash code provider by supplying an implementation to one of the overloads of the class constructor. ## Notes for the Windows Runtime -When you call the method on a class in the Windows Runtime, it provides the default behavior for classes that don't override . This is part of the support that .NET provides for the Windows Runtime (see [.NET Support for Windows Store Apps and Windows Runtime](/dotnet/standard/cross-platform/support-for-windows-store-apps-and-windows-runtime)). Classes in the Windows Runtime don't inherit , and currently don't implement a . However, they appear to have , , and methods when you use them in your C# or Visual Basic code, and the .NET Framework provides the default behavior for these methods. +When you call the method on a class in the Windows Runtime, it provides the default behavior for classes that don't override . This is part of the support that .NET provides for the Windows Runtime (see [.NET Support for Windows Store Apps and Windows Runtime](/dotnet/standard/cross-platform/support-for-windows-store-apps-and-windows-runtime)). Classes in the Windows Runtime don't inherit , and currently don't implement a . However, they appear to have , , and methods when you use them in your C# or Visual Basic code, and the .NET Framework provides the default behavior for these methods. > [!NOTE] -> Windows Runtime classes that are written in C# or Visual Basic can override the method. +> Windows Runtime classes that are written in C# or Visual Basic can override the method. ## Examples @@ -58,7 +58,7 @@ Frequently, a type has multiple data fields that can participate in generating t :::code language="fsharp" source="./snippets/System/Object/GetHashCode/fsharp/xor1.fs" id="Snippet2"::: :::code language="vb" source="./snippets/System/Object/GetHashCode/vb/xor1.vb" id="Snippet2"::: -The previous example returns the same hash code for (n1, n2) and (n2, n1), and so may generate more collisions than are desirable. A number of solutions are available so that hash codes in these cases are not identical. One is to return the hash code of a `Tuple` object that reflects the order of each field. The following example shows a possible implementation that uses the class. Note, though, that the performance overhead of instantiating a `Tuple` object may significantly impact the overall performance of an application that stores large numbers of objects in hash tables. +The previous example returns the same hash code for (n1, n2) and (n2, n1), and so may generate more collisions than are desirable. A number of solutions are available so that hash codes in these cases are not identical. One is to return the hash code of a `Tuple` object that reflects the order of each field. The following example shows a possible implementation that uses the class. Note, though, that the performance overhead of instantiating a `Tuple` object may significantly impact the overall performance of an application that stores large numbers of objects in hash tables. :::code language="csharp" source="./snippets/System/Object/GetHashCode/csharp/xor2.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/Object/GetHashCode/fsharp/xor2.fs" id="Snippet3"::: diff --git a/docs/fundamentals/runtime-libraries/system-object-tostring.md b/docs/fundamentals/runtime-libraries/system-object-tostring.md index 6f7017fc24b64..2eea195877c6e 100644 --- a/docs/fundamentals/runtime-libraries/system-object-tostring.md +++ b/docs/fundamentals/runtime-libraries/system-object-tostring.md @@ -11,22 +11,22 @@ dev_langs: [!INCLUDE [context](includes/context.md)] - is a common formatting method in .NET. It converts an object to its string representation so that it is suitable for display. (For information about formatting support in .NET, see [Formatting Types](../../standard/base-types/formatting-types.md).) Default implementations of the method return the fully qualified name of the object's type. + is a common formatting method in .NET. It converts an object to its string representation so that it is suitable for display. (For information about formatting support in .NET, see [Formatting Types](../../standard/base-types/formatting-types.md).) Default implementations of the method return the fully qualified name of the object's type. > [!IMPORTANT] -> You may have reached this page by following the link from the member list of another type. That is because that type does not override . Instead, it inherits the functionality of the method. +> You may have reached this page by following the link from the member list of another type. That is because that type does not override . Instead, it inherits the functionality of the method. -Types frequently override the method to provide a more suitable string representation of a particular type. Types also frequently overload the method to provide support for format strings or culture-sensitive formatting. +Types frequently override the method to provide a more suitable string representation of a particular type. Types also frequently overload the method to provide support for format strings or culture-sensitive formatting. ## The default Object.ToString() method -The default implementation of the method returns the fully qualified name of the type of the , as the following example shows. +The default implementation of the method returns the fully qualified name of the type of the , as the following example shows. :::code language="csharp" source="./snippets/System/Object/ToString/csharp/tostring1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/tostring1.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/Object/ToString/vb/tostring1.vb" id="Snippet1"::: -Because is the base class of all reference types in .NET, this behavior is inherited by reference types that do not override the method. The following example illustrates this. It defines a class named `Object1` that accepts the default implementation of all members. Its method returns the object's fully qualified type name. +Because is the base class of all reference types in .NET, this behavior is inherited by reference types that do not override the method. The following example illustrates this. It defines a class named `Object1` that accepts the default implementation of all members. Its method returns the object's fully qualified type name. :::code language="csharp" source="./snippets/System/Object/ToString/csharp/tostring2.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/tostring2.fs" id="Snippet2"::: @@ -34,23 +34,23 @@ Because is the base class of all reference types in .NET, t ## Override the Object.ToString() method -Types commonly override the method to return a string that represents the object instance. For example, the base types such as , , and provide implementations that return the string form of the value that the object represents. The following example defines a class, `Object2`, that overrides the method to return the type name along with its value. +Types commonly override the method to return a string that represents the object instance. For example, the base types such as , , and provide implementations that return the string form of the value that the object represents. The following example defines a class, `Object2`, that overrides the method to return the type name along with its value. :::code language="csharp" source="./snippets/System/Object/ToString/csharp/tostring3.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/tostring3.fs" id="Snippet3"::: :::code language="vb" source="./snippets/System/Object/ToString/vb/tostring3.vb" id="Snippet3"::: -The following table lists the type categories in .NET and indicates whether or not they override the method. +The following table lists the type categories in .NET and indicates whether or not they override the method. | Type category | Overrides Object.ToString() | Behavior | |---------------|-----------------------------|----------| | Class | n/a | n/a | -| Structure | Yes () | Same as `Object.ToString()` | +| Structure | Yes () | Same as `Object.ToString()` | | Enumeration | Yes () | The member name | | Interface | No| n/a | | Delegate | No| n/a | -See the Notes to Inheritors section for additional information on overriding . +See the Notes to Inheritors section for additional information on overriding . ## Overload the ToString method @@ -72,7 +72,7 @@ For more information on format strings and culture-sensitive formatting, see [Fo ## Extend the Object.ToString method -Because a type inherits the default method, you may find its behavior undesirable and want to change it. This is particularly true of arrays and collection classes. While you may expect the `ToString` method of an array or collection class to display the values of its members, it instead displays the type fully qualified type name, as the following example shows. +Because a type inherits the default method, you may find its behavior undesirable and want to change it. This is particularly true of arrays and collection classes. While you may expect the `ToString` method of an array or collection class to display the values of its members, it instead displays the type fully qualified type name, as the following example shows. :::code language="csharp" source="./snippets/System/Object/ToString/csharp/array1.cs" id="Snippet6"::: :::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/array1.fs" id="Snippet6"::: @@ -80,22 +80,22 @@ Because a type inherits the default or interfaces, you can enumerate its elements by using the `foreach` statement in C# or the `For Each...Next` construct in Visual Basic. +- If the type is an array, a collection object, or an object that implements the or interfaces, you can enumerate its elements by using the `foreach` statement in C# or the `For Each...Next` construct in Visual Basic. -- If the class is not `sealed` (in C#) or `NotInheritable` (in Visual Basic), you can develop a wrapper class that inherits from the base class whose method you want to customize. At a minimum, this requires that you do the following: +- If the class is not `sealed` (in C#) or `NotInheritable` (in Visual Basic), you can develop a wrapper class that inherits from the base class whose method you want to customize. At a minimum, this requires that you do the following: 1. Implement any necessary constructors. Derived classes do not inherit their base class constructors. - 2. Override the method to return the result string that you'd like. + 2. Override the method to return the result string that you'd like. - The following example defines a wrapper class for the class. It overrides the method to display the value of each method of the collection rather than the fully qualified type name. + The following example defines a wrapper class for the class. It overrides the method to display the value of each method of the collection rather than the fully qualified type name. :::code language="csharp" source="./snippets/System/Object/ToString/csharp/customize1.cs" id="Snippet7"::: :::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/customize1.fs" id="Snippet7"::: :::code language="vb" source="./snippets/System/Object/ToString/vb/customize1.vb" id="Snippet7"::: -- Develop an [extension method](../../standard/design-guidelines/extension-methods.md) that returns the result string that you want. Note that you can't override the default method in this way—that is, your extension class (in C#) or module (in Visual Basic) cannot have a parameterless method named `ToString` that's called in place of the original type's `ToString` method. You'll have to provide some other name for your parameterless `ToString` replacement. +- Develop an [extension method](../../standard/design-guidelines/extension-methods.md) that returns the result string that you want. Note that you can't override the default method in this way—that is, your extension class (in C#) or module (in Visual Basic) cannot have a parameterless method named `ToString` that's called in place of the original type's `ToString` method. You'll have to provide some other name for your parameterless `ToString` replacement. - The following example defines two methods that extend the class: a parameterless `ToString2` method, and a `ToString` method with a parameter that represents a format string. + The following example defines two methods that extend the class: a parameterless `ToString2` method, and a `ToString` method with a parameter that represents a format string. :::code language="csharp" source="./snippets/System/Object/ToString/csharp/customize2.cs" id="Snippet8"::: :::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/customize2.fs" id="Snippet8"::: @@ -103,18 +103,18 @@ You have several options to produce the result string that you'd like. ## Notes for the Windows Runtime -When you call the method on a class in the Windows Runtime, it provides the default behavior for classes that don't override . This is part of the support that .NET provides for the Windows Runtime (see [.NET Support for Windows Store Apps and Windows Runtime](/dotnet/standard/cross-platform/support-for-windows-store-apps-and-windows-runtime)). Classes in the Windows Runtime don't inherit , and don't always implement a . However, they always appear to have , , and methods when you use them in your C# or Visual Basic code, and .NET provides a default behavior for these methods. +When you call the method on a class in the Windows Runtime, it provides the default behavior for classes that don't override . This is part of the support that .NET provides for the Windows Runtime (see [.NET Support for Windows Store Apps and Windows Runtime](/dotnet/standard/cross-platform/support-for-windows-store-apps-and-windows-runtime)). Classes in the Windows Runtime don't inherit , and don't always implement a . However, they always appear to have , , and methods when you use them in your C# or Visual Basic code, and .NET provides a default behavior for these methods. -The common language runtime uses [IStringable.ToString](xref:Windows.Foundation.IStringable.ToString) on a Windows Runtime object before falling back to the default implementation of . +The common language runtime uses [IStringable.ToString](xref:Windows.Foundation.IStringable.ToString) on a Windows Runtime object before falling back to the default implementation of . > [!NOTE] -> Windows Runtime classes that are written in C# or Visual Basic can override the method. +> Windows Runtime classes that are written in C# or Visual Basic can override the method. ### The Windows Runtime and the IStringable Interface -The Windows Runtime includes an [IStringable](xref:Windows.Foundation.IStringable) interface whose single method, [IStringable.ToString](xref:Windows.Foundation.IStringable.ToString), provides basic formatting support comparable to that provided by . To prevent ambiguity, you should not implement [IStringable](xref:Windows.Foundation.IStringable) on managed types. +The Windows Runtime includes an [IStringable](xref:Windows.Foundation.IStringable) interface whose single method, [IStringable.ToString](xref:Windows.Foundation.IStringable.ToString), provides basic formatting support comparable to that provided by . To prevent ambiguity, you should not implement [IStringable](xref:Windows.Foundation.IStringable) on managed types. -When managed objects are called by native code or by code written in languages such as JavaScript or C++/CX, they appear to implement [IStringable](xref:Windows.Foundation.IStringable). The common language runtime automatically routes calls from [IStringable.ToString](xref:Windows.Foundation.IStringable.ToString) to if [IStringable](xref:Windows.Foundation.IStringable) is not implemented on the managed object. +When managed objects are called by native code or by code written in languages such as JavaScript or C++/CX, they appear to implement [IStringable](xref:Windows.Foundation.IStringable). The common language runtime automatically routes calls from [IStringable.ToString](xref:Windows.Foundation.IStringable.ToString) to if [IStringable](xref:Windows.Foundation.IStringable) is not implemented on the managed object. > [!WARNING] > Because the common language runtime auto-implements [IStringable](xref:Windows.Foundation.IStringable) for all managed types in Windows Store apps, we recommend that you do not provide your own `IStringable` implementation. Implementing `IStringable` may result in unintended behavior when calling `ToString` from the Windows Runtime, C++/CX, or JavaScript. diff --git a/docs/fundamentals/runtime-libraries/system-object.md b/docs/fundamentals/runtime-libraries/system-object.md index 19d1359d57179..37c063ebb20f7 100644 --- a/docs/fundamentals/runtime-libraries/system-object.md +++ b/docs/fundamentals/runtime-libraries/system-object.md @@ -11,10 +11,10 @@ The class is the ultimate base class of all .NET classes; i Because all classes in .NET are derived from , every method defined in the class is available in all objects in the system. Derived classes can and do override some of these methods, including: -- : Supports comparisons between objects. -- : Performs cleanup operations before an object is automatically reclaimed. -- : Generates a number corresponding to the value of the object to support the use of a hash table. -- : Manufactures a human-readable text string that describes an instance of the class. +- : Supports comparisons between objects. +- : Performs cleanup operations before an object is automatically reclaimed. +- : Generates a number corresponding to the value of the object to support the use of a hash table. +- : Manufactures a human-readable text string that describes an instance of the class. Languages typically don't require a class to declare inheritance from because the inheritance is implicit. diff --git a/docs/fundamentals/runtime-libraries/system-random.md b/docs/fundamentals/runtime-libraries/system-random.md index d9e608a46b797..6085b1e17d177 100644 --- a/docs/fundamentals/runtime-libraries/system-random.md +++ b/docs/fundamentals/runtime-libraries/system-random.md @@ -19,16 +19,16 @@ To generate a cryptographically secure random number, such as one that's suitabl ## Instantiate the random number generator -You instantiate the random number generator by providing a seed value (a starting value for the pseudo-random number generation algorithm) to a class constructor. You can supply the seed value either explicitly or implicitly: +You instantiate the random number generator by providing a seed value (a starting value for the pseudo-random number generation algorithm) to a class constructor. You can supply the seed value either explicitly or implicitly: -- The constructor uses an explicit seed value that you supply. +- The constructor uses an explicit seed value that you supply. - The constructor uses the default seed value. This is the most common way of instantiating the random number generator. In .NET Framework, the default seed value is time-dependent. In .NET Core, the default seed value is produced by the thread-static, pseudo-random number generator. If the same seed is used for separate objects, they will generate the same series of random numbers. This can be useful for creating a test suite that processes random values, or for replaying games that derive their data from random numbers. However, note that objects in processes running under different versions of .NET Framework might return differentseries of random numbers even if they're instantiated with identical seed values. -To produce different sequences of random numbers, you can make the seed value time-dependent, thereby producing a different series with each new instance of . The parameterized constructor can take an value based on the number of ticks in the current time, whereas the parameterless constructor uses the system clock to generate its seed value. However, on .NET Framework only, because the clock has finite resolution, using the parameterless constructor to create different objects in close succession creates random number generators that produce identical sequences of random numbers. The following example illustrates how two objects that are instantiated in close succession in a .NET Framework application generate an identical series of random numbers. On most Windows systems, objects created within 15 milliseconds of one another are likely to have identical seed values. +To produce different sequences of random numbers, you can make the seed value time-dependent, thereby producing a different series with each new instance of . The parameterized constructor can take an value based on the number of ticks in the current time, whereas the parameterless constructor uses the system clock to generate its seed value. However, on .NET Framework only, because the clock has finite resolution, using the parameterless constructor to create different objects in close succession creates random number generators that produce identical sequences of random numbers. The following example illustrates how two objects that are instantiated in close succession in a .NET Framework application generate an identical series of random numbers. On most Windows systems, objects created within 15 milliseconds of one another are likely to have identical seed values. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/Random1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/Random1.fs" id="Snippet1"::: @@ -60,7 +60,7 @@ The example ensures thread-safety in the following ways: - A lock (the `lock` statement in C#, the `lock` function in F# and the `SyncLock` statement in Visual Basic) protects access to the variables for the total count and sum of all random numbers generated on all threads. - A semaphore (the object) is used to ensure that the main thread blocks until all other threads complete execution. - The example checks whether the random number generator has become corrupted by determining whether two consecutive calls to random number generation methods return 0. If corruption is detected, the example uses the object to signal that all threads should be canceled. -- Before generating each random number, each thread checks the state of the object. If cancellation is requested, the example calls the method to cancel the thread. +- Before generating each random number, each thread checks the state of the object. If cancellation is requested, the example calls the method to cancel the thread. The following example is identical to the first, except that it uses a object and a lambda expression instead of objects. @@ -71,49 +71,49 @@ The following example is identical to the first, except that it uses a attribute. -- The static method is used to ensure that the main thread doesn't complete before all tasks have finished. There is no need for the object. -- The exception that results from task cancellation is surfaced in the method. In the previous example, it is handled by each thread. +- The static method is used to ensure that the main thread doesn't complete before all tasks have finished. There is no need for the object. +- The exception that results from task cancellation is surfaced in the method. In the previous example, it is handled by each thread. ## Generate different types of random numbers The random number generator provides methods that let you generate the following kinds of random numbers: -- A series of values. You determine the number of byte values by passing an array initialized to the number of elements you want the method to return to the method. The following example generates 20 bytes. +- A series of values. You determine the number of byte values by passing an array initialized to the number of elements you want the method to return to the method. The following example generates 20 bytes. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/nextbytes1.cs" id="Snippet5"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/nextbytes1.fs" id="Snippet5"::: :::code language="vb" source="./snippets/System/Random/Overview/vb/nextbytes1.vb" id="Snippet5"::: -- A single integer. You can choose whether you want an integer from 0 to a maximum value ( - 1) by calling the method, an integer between 0 and a specific value by calling the method, or an integer within a range of values by calling the method. In the parameterized overloads, the specified maximum value is exclusive; that is, the actual maximum number generated is one less than the specified value. +- A single integer. You can choose whether you want an integer from 0 to a maximum value ( - 1) by calling the method, an integer between 0 and a specific value by calling the method, or an integer within a range of values by calling the method. In the parameterized overloads, the specified maximum value is exclusive; that is, the actual maximum number generated is one less than the specified value. - The following example calls the method to generate 10 random numbers between -10 and 10. Note that the second argument to the method specifies the exclusive upper bound of the range of random values returned by the method. In other words, the largest integer that the method can return is one less than this value. + The following example calls the method to generate 10 random numbers between -10 and 10. Note that the second argument to the method specifies the exclusive upper bound of the range of random values returned by the method. In other words, the largest integer that the method can return is one less than this value. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/nextex1.cs" id="Snippet6"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/nextex1.fs" id="Snippet6"::: :::code language="vb" source="./snippets/System/Random/Overview/vb/nextex1.vb" id="Snippet6"::: -- A single floating-point value from 0.0 to less than 1.0 by calling the method. The exclusive upper bound of the random number returned by the method is 1, so its actual upper bound is 0.99999999999999978. The following example generates 10 random floating-point numbers. +- A single floating-point value from 0.0 to less than 1.0 by calling the method. The exclusive upper bound of the random number returned by the method is 1, so its actual upper bound is 0.99999999999999978. The following example generates 10 random floating-point numbers. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/nextdoubleex1.cs" id="Snippet7"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/nextdoubleex1.fs" id="Snippet7"::: :::code language="vb" source="./snippets/System/Random/Overview/vb/nextdoubleex1.vb" id="Snippet7"::: > [!IMPORTANT] -> The method allows you to specify the range of the returned random number. However, the `maxValue` parameter, which specifies the upper range returned number, is an exclusive, not an inclusive, value. This means that the method call `Next(0, 100)` returns a value between 0 and 99, and not between 0 and 100. +> The method allows you to specify the range of the returned random number. However, the `maxValue` parameter, which specifies the upper range returned number, is an exclusive, not an inclusive, value. This means that the method call `Next(0, 100)` returns a value between 0 and 99, and not between 0 and 100. You can also use the class for such tasks as generating [random Boolean values](#generate-random-boolean-values), generating [random floating-point values in a specified range](#retrieve-floating-point-values-in-a-specified-range), generating [Generate random 64-bit integers](#generate-random-64-bit-integers), and [retrieving a unique element from an array or collection](#retrieve-a-unique-element-from-an-array-or-collection). ## Substitute your own algorithm -You can implement your own random number generator by inheriting from the class and supplying your random number generation algorithm. To supply your own algorithm, you must override the method, which implements the random number generation algorithm. You should also override the , , and methods to ensure that they call your overridden method. You don't have to override the and methods. +You can implement your own random number generator by inheriting from the class and supplying your random number generation algorithm. To supply your own algorithm, you must override the method, which implements the random number generation algorithm. You should also override the , , and methods to ensure that they call your overridden method. You don't have to override the and methods. -For an example that derives from the class and modifies its default pseudo-random number generator, see the reference page. +For an example that derives from the class and modifies its default pseudo-random number generator, see the reference page. ## Retrieve the same sequence of random values Sometimes you want to generate the same sequence of random numbers in software test scenarios and in game playing. Testing with the same sequence of random numbers allows you to detect regressions and confirm bug fixes. Using the same sequence of random number in games allows you to replay previous games. -You can generate the same sequence of random numbers by providing the same seed value to the constructor. The seed value provides a starting value for the pseudo-random number generation algorithm. The following example uses 100100 as an arbitrary seed value to instantiate the object, displays 20 random floating-point values, and persists the seed value. It then restores the seed value, instantiates a new random number generator, and displays the same 20 random floating-point values. Note that the example may produce different sequences of random numbers if run on different versions of .NET. +You can generate the same sequence of random numbers by providing the same seed value to the constructor. The seed value provides a starting value for the pseudo-random number generation algorithm. The following example uses 100100 as an arbitrary seed value to instantiate the object, displays 20 random floating-point values, and persists the seed value. It then restores the seed value, instantiates a new random number generator, and displays the same 20 random floating-point values. Note that the example may produce different sequences of random numbers if run on different versions of .NET. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/same1.cs" id="Snippet12"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/same1.fs" id="Snippet12"::: @@ -121,19 +121,19 @@ You can generate the same sequence of random numbers by providing the same seed ## Retrieve unique sequences of random numbers -Providing different seed values to instances of the class causes each random number generator to produce a different sequence of values. You can provide a seed value either explicitly by calling the constructor, or implicitly by calling the constructor. Most developers call the parameterless constructor, which uses the system clock. The following example uses this approach to instantiate two instances. Each instance displays a series of 10 random integers. +Providing different seed values to instances of the class causes each random number generator to produce a different sequence of values. You can provide a seed value either explicitly by calling the constructor, or implicitly by calling the constructor. Most developers call the parameterless constructor, which uses the system clock. The following example uses this approach to instantiate two instances. Each instance displays a series of 10 random integers. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/unique.cs" id="Snippet13"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/unique.fs" id="Snippet13"::: :::code language="vb" source="./snippets/System/Random/Overview/vb/unique.vb" id="Snippet13"::: -However, because of its finite resolution, the system clock doesn't detect time differences that are less than approximately 15 milliseconds. Therefore, if your code calls the overload on .NET Framework to instantiate two objects in succession, you might inadvertently be providing the objects with identical seed values. (The class in .NET Core does not have this limitation.) To see this in the previous example, comment out the method call, and compile and run the example again. +However, because of its finite resolution, the system clock doesn't detect time differences that are less than approximately 15 milliseconds. Therefore, if your code calls the overload on .NET Framework to instantiate two objects in succession, you might inadvertently be providing the objects with identical seed values. (The class in .NET Core does not have this limitation.) To see this in the previous example, comment out the method call, and compile and run the example again. -To prevent this from happening, we recommend that you instantiate a single object rather than multiple ones. However, since isn't thread safe, you must use some synchronization device if you access a instance from multiple threads; for more information, see the [Thread safety](#thread-safety) section. Alternately, you can use a delay mechanism, such as the method used in the previous example, to ensure that the instantiations occur more than 15 millisecond apart. +To prevent this from happening, we recommend that you instantiate a single object rather than multiple ones. However, since isn't thread safe, you must use some synchronization device if you access a instance from multiple threads; for more information, see the [Thread safety](#thread-safety) section. Alternately, you can use a delay mechanism, such as the method used in the previous example, to ensure that the instantiations occur more than 15 millisecond apart. ## Retrieve integers in a specified range -You can retrieve integers in a specified range by calling the method, which lets you specify both the lower and the upper bound of the numbers you'd like the random number generator to return. The upper bound is an exclusive, not an inclusive, value. That is, it isn't included in the range of values returned by the method. The following example uses this method to generate random integers between -10 and 10. Note that it specifies 11, which is one greater than the desired value, as the value of the `maxValue` argument in the method call. +You can retrieve integers in a specified range by calling the method, which lets you specify both the lower and the upper bound of the numbers you'd like the random number generator to return. The upper bound is an exclusive, not an inclusive, value. That is, it isn't included in the range of values returned by the method. The following example uses this method to generate random integers between -10 and 10. Note that it specifies 11, which is one greater than the desired value, as the value of the `maxValue` argument in the method call. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/range1.cs" id="Snippet15"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/range1.fs" id="Snippet15"::: @@ -141,7 +141,7 @@ You can retrieve integers in a specified range by calling the method to retrieve numbers with a specified number of digits. For example, to retrieve numbers with four digits (that is, numbers that range from 1000 to 9999), you call the method with a `minValue` value of 1000 and a `maxValue` value of 10000, as the following example shows. +You can call the method to retrieve numbers with a specified number of digits. For example, to retrieve numbers with four digits (that is, numbers that range from 1000 to 9999), you call the method with a `minValue` value of 1000 and a `maxValue` value of 10000, as the following example shows. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/range2.cs" id="Snippet16"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/range2.fs" id="Snippet16"::: @@ -149,9 +149,9 @@ You can call the meth ## Retrieve floating-point values in a specified range -The method returns random floating-point values that range from 0 to less than 1. However, you'll often want to generate random values in some other range. +The method returns random floating-point values that range from 0 to less than 1. However, you'll often want to generate random values in some other range. -If the interval between the minimum and maximum desired values is 1, you can add the difference between the desired starting interval and 0 to the number returned by the method. The following example does this to generate 10 random numbers between -1 and 0. +If the interval between the minimum and maximum desired values is 1, you can add the difference between the desired starting interval and 0 to the number returned by the method. The following example does this to generate 10 random numbers between -1 and 0. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/doublerange2.cs" id="Snippet17"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/doublerange2.fs" id="Snippet17"::: @@ -163,7 +163,7 @@ To generate random floating-point numbers whose lower bound is 0 but upper bound :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/doublerange1.fs" id="Snippet18"::: :::code language="vb" source="./snippets/System/Random/Overview/vb/doublerange1.vb" id="Snippet18"::: -To generate random floating-point numbers between two arbitrary values, like the method does for integers, use the following formula: +To generate random floating-point numbers between two arbitrary values, like the method does for integers, use the following formula: ```csharp Random.NextDouble() * (maxValue - minValue) + minValue @@ -177,7 +177,7 @@ The following example generates 1 million random numbers that range from 10.0 to ## Generate random Boolean values -The class doesn't provide methods that generate values. However, you can define your own class or method to do that. The following example defines a class, `BooleanGenerator`, with a single method, `NextBoolean`. The `BooleanGenerator` class stores a object as a private variable. The `NextBoolean` method calls the method and passes the result to the method. Note that 2 is used as the argument to specify the upper bound of the random number. Since this is an exclusive value, the method call returns either 0 or 1. +The class doesn't provide methods that generate values. However, you can define your own class or method to do that. The following example defines a class, `BooleanGenerator`, with a single method, `NextBoolean`. The `BooleanGenerator` class stores a object as a private variable. The `NextBoolean` method calls the method and passes the result to the method. Note that 2 is used as the argument to specify the upper bound of the random number. Since this is an exclusive value, the method call returns either 0 or 1. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/booleans1.cs" id="Snippet8"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/booleans1.fs" id="Snippet8"::: @@ -191,9 +191,9 @@ Instead of creating a separate class to generate random va ## Generate random 64-bit integers -The overloads of the method return 32-bit integers. However, in some cases, you might want to work with 64-bit integers. You can do this as follows: +The overloads of the method return 32-bit integers. However, in some cases, you might want to work with 64-bit integers. You can do this as follows: -1. Call the method to retrieve a double-precision floating point value. +1. Call the method to retrieve a double-precision floating point value. 2. Multiply that value by . @@ -211,17 +211,17 @@ An alternative technique that uses bit manipulation does not generate truly rand ## Retrieve bytes in a specified range -The overloads of the method allow you to specify the range of random numbers, but the method does not. The following example implements a `NextBytes` method that lets you specify the range of the returned bytes. It defines a `Random2` class that derives from and overloads its `NextBytes` method. +The overloads of the method allow you to specify the range of random numbers, but the method does not. The following example implements a `NextBytes` method that lets you specify the range of the returned bytes. It defines a `Random2` class that derives from and overloads its `NextBytes` method. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/bytes1.cs" id="Snippet9"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/bytes1.fs" id="Snippet9"::: :::code language="vb" source="./snippets/System/Random/Overview/vb/bytes1.vb" id="Snippet9"::: -The `NextBytes(Byte[], Byte, Byte)` method wraps a call to the method and specifies the minimum value and one greater than the maximum value (in this case, 0 and 101) that we want returned in the byte array. Because we are sure that the integer values returned by the method are within the range of the data type, we can safely cast them (in C# and F#) or convert them (in Visual Basic) from integers to bytes. +The `NextBytes(Byte[], Byte, Byte)` method wraps a call to the method and specifies the minimum value and one greater than the maximum value (in this case, 0 and 101) that we want returned in the byte array. Because we are sure that the integer values returned by the method are within the range of the data type, we can safely cast them (in C# and F#) or convert them (in Visual Basic) from integers to bytes. ## Retrieve an element from an array or collection at random -Random numbers often serve as indexes to retrieve values from arrays or collections. To retrieve a random index value, you can call the method, and use the lower bound of the array as the value of its `minValue` argument and one greater than the upper bound of the array as the value of its `maxValue` argument. For a zero-based array, this is equivalent to its property, or one greater than the value returned by the method. The following example randomly retrieves the name of a city in the United States from an array of cities. +Random numbers often serve as indexes to retrieve values from arrays or collections. To retrieve a random index value, you can call the method, and use the lower bound of the array as the value of its `minValue` argument and one greater than the upper bound of the array as the value of its `maxValue` argument. For a zero-based array, this is equivalent to its property, or one greater than the value returned by the method. The following example randomly retrieves the name of a city in the United States from an array of cities. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/array1.cs" id="Snippet10"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/array1.fs" id="Snippet10"::: @@ -231,11 +231,11 @@ Random numbers often serve as indexes to retrieve values from arrays or collecti A random number generator can always return duplicate values. As the range of numbers becomes smaller or the number of values generated becomes larger, the probability of duplicates grows. If random values must be unique, more numbers are generated to compensate for duplicates, resulting in increasingly poor performance. -There are a number of techniques to handle this scenario. One common solution is to create an array or collection that contains the values to be retrieved, and a parallel array that contains random floating-point numbers. The second array is populated with random numbers at the time the first array is created, and the method is used to sort the first array by using the values in the parallel array. +There are a number of techniques to handle this scenario. One common solution is to create an array or collection that contains the values to be retrieved, and a parallel array that contains random floating-point numbers. The second array is populated with random numbers at the time the first array is created, and the method is used to sort the first array by using the values in the parallel array. For example, if you're developing a Solitaire game, you want to ensure that each card is used only once. Instead of generating random numbers to retrieve a card and tracking whether that card has already been dealt, you can create a parallel array of random numbers that can be used to sort the deck. Once the deck is sorted, your app can maintain a pointer to indicate the index of the next card on the deck. -The following example illustrates this approach. It defines a `Card` class that represents a playing card and a `Dealer` class that deals a deck of shuffled cards. The `Dealer` class constructor populates two arrays: a `deck` array that has class scope and that represents all the cards in the deck; and a local `order` array that has the same number of elements as the `deck` array and is populated with randomly generated values. The method is then called to sort the `deck` array based on the values in the `order` array. +The following example illustrates this approach. It defines a `Card` class that represents a playing card and a `Dealer` class that deals a deck of shuffled cards. The `Dealer` class constructor populates two arrays: a `deck` array that has class scope and that represents all the cards in the deck; and a local `order` array that has the same number of elements as the `deck` array and is populated with randomly generated values. The method is then called to sort the `deck` array based on the values in the `order` array. :::code language="csharp" source="./snippets/System/Random/Overview/csharp/uniquearray1.cs" id="Snippet11"::: :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/uniquearray1.fs" id="Snippet11"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-assemblybuilder.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-assemblybuilder.md index 365915ef93bf1..7c43a74f38e88 100644 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-assemblybuilder.md +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-assemblybuilder.md @@ -13,7 +13,7 @@ The way you create an instance dif ## Runnable dynamic assemblies in .NET -To get a runnable object, use the method. +To get a runnable object, use the method. Dynamic assemblies can be created using one of the following access modes: - @@ -24,7 +24,7 @@ Dynamic assemblies can be created using one of the following access modes: The dynamic assembly represented by an can be used to execute the emitted code and is automatically reclaimed by garbage collector. -The access mode must be specified by providing the appropriate value in the call to the method when the dynamic assembly is defined and cannot be changed later. The runtime uses the access mode of a dynamic assembly to optimize the assembly's internal representation. +The access mode must be specified by providing the appropriate value in the call to the method when the dynamic assembly is defined and cannot be changed later. The runtime uses the access mode of a dynamic assembly to optimize the assembly's internal representation. The following example demonstrates how to create and run an assembly: @@ -57,7 +57,7 @@ In .NET, the type, which In .NET Framework, dynamic assemblies and modules can be saved to files. To support this feature, the enumeration declares two additional fields: and . -The dynamic modules in the persistable dynamic assembly are saved when the dynamic assembly is saved using the method. To generate an executable, the method must be called to identify the method that is the entry point to the assembly. Assemblies are saved as DLLs by default, unless the method requests the generation of a console application or a Windows-based application. +The dynamic modules in the persistable dynamic assembly are saved when the dynamic assembly is saved using the method. To generate an executable, the method must be called to identify the method that is the entry point to the assembly. Assemblies are saved as DLLs by default, unless the method requests the generation of a console application or a Windows-based application. The following example demonstrates how to create, save, and run an assembly using .NET Framework. @@ -83,9 +83,9 @@ public void CreateRunAndSaveAssembly(string assemblyPath) } ``` -Some methods on the base class, such as `GetModules` and `GetLoadedModules`, won't work correctly when called from objects. You can load the defined dynamic assembly and call the methods on the loaded assembly. For example, to ensure that resource modules are included in the returned module list, call `GetModules` on the loaded object. If a dynamic assembly contains more than one dynamic module, the assembly's manifest file name should match the module's name that's specified as the first argument to the method. +Some methods on the base class, such as `GetModules` and `GetLoadedModules`, won't work correctly when called from objects. You can load the defined dynamic assembly and call the methods on the loaded assembly. For example, to ensure that resource modules are included in the returned module list, call `GetModules` on the loaded object. If a dynamic assembly contains more than one dynamic module, the assembly's manifest file name should match the module's name that's specified as the first argument to the method. -The signing of a dynamic assembly using is not effective until the assembly is saved to disk. So, strong names will not work with transient dynamic assemblies. +The signing of a dynamic assembly using is not effective until the assembly is saved to disk. So, strong names will not work with transient dynamic assemblies. Dynamic assemblies can reference types defined in another assembly. A transient dynamic assembly can safely reference types defined in another transient dynamic assembly, a persistable dynamic assembly, or a static assembly. However, the common language runtime does not allow a persistable dynamic module to reference a type defined in a transient dynamic module. This is because when the persisted dynamic module is loaded after being saved to disk, the runtime cannot resolve the references to types defined in the transient dynamic module. diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-methodbuilder.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-methodbuilder.md index 4d1dffa1f5a7a..7fd1afe4b3f28 100644 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-methodbuilder.md +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-methodbuilder.md @@ -13,17 +13,17 @@ You can use reflection emit to define global methods and to define methods as ty ## Global methods -A global method is defined by using the method, which returns a `MethodBuilder` object. +A global method is defined by using the method, which returns a `MethodBuilder` object. -Global methods must be static. If a dynamic module contains global methods, the method must be called before persisting the dynamic module or the containing dynamic assembly because the common language runtime postpones fixing up the dynamic module until all global functions have been defined. +Global methods must be static. If a dynamic module contains global methods, the method must be called before persisting the dynamic module or the containing dynamic assembly because the common language runtime postpones fixing up the dynamic module until all global functions have been defined. -A global native method is defined by using the method. Platform invoke (PInvoke) methods must not be declared abstract or virtual. The runtime sets the attribute for a platform invoke method. +A global native method is defined by using the method. Platform invoke (PInvoke) methods must not be declared abstract or virtual. The runtime sets the attribute for a platform invoke method. ## Methods as members of types -A method is defined as a type member by using the method, which returns a object. +A method is defined as a type member by using the method, which returns a object. -The method is used to set the name and parameter attributes of a parameter, or of the return value. The object returned by this method represents a parameter or the return value. The object can be used to set the marshaling, to set the constant value, and to apply custom attributes. +The method is used to set the name and parameter attributes of a parameter, or of the return value. The object returned by this method represents a parameter or the return value. The object can be used to set the marshaling, to set the constant value, and to apply custom attributes. ## Attributes @@ -39,5 +39,5 @@ Members of the enumeration define the ## Known issues -- Although is derived from , some of the abstract methods defined in the class are not fully implemented in . These methods throw the . For example the method is not fully implemented. You can reflect on these methods by retrieving the enclosing type using the or methods. +- Although is derived from , some of the abstract methods defined in the class are not fully implemented in . These methods throw the . For example the method is not fully implemented. You can reflect on these methods by retrieving the enclosing type using the or methods. - Custom modifiers are supported. diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-persistedassemblybuilder.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-persistedassemblybuilder.md index 4d995e4757b63..f9758897ffddd 100644 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-persistedassemblybuilder.md +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-persistedassemblybuilder.md @@ -7,7 +7,7 @@ ms.date: 05/10/2024 [!INCLUDE [context](includes/context.md)] -The API wasn't originally ported to .NET (Core) because the implementation depended heavily on Windows-specific native code that also wasn't ported. .NET 9 added the class, which provides a fully managed `Reflection.Emit` implementation that supports saving. This implementation has no dependency on the pre-existing, runtime-specific `Reflection.Emit` implementation. That is, now there are two different implementations in .NET: *runnable* and *persisted*. To run the persisted assembly, first save it into a memory stream or a file, then load it back. +The API wasn't originally ported to .NET (Core) because the implementation depended heavily on Windows-specific native code that also wasn't ported. .NET 9 added the class, which provides a fully managed `Reflection.Emit` implementation that supports saving. This implementation has no dependency on the pre-existing, runtime-specific `Reflection.Emit` implementation. That is, now there are two different implementations in .NET: *runnable* and *persisted*. To run the persisted assembly, first save it into a memory stream or a file, then load it back. Before `PersistedAssemblyBuilder`, you could only run a generated assembly and not save it. Since the assembly was in-memory only, it was difficult to debug. Advantages of saving a dynamic assembly to a file are: @@ -37,7 +37,7 @@ The symbols metadata is populated into the `pdbBuilder` out parameter when you c 1. Create instances with the method. While emitting the method's IL, also emit the corresponding symbol info. 2. Create a instance using the `pdbBuilder` instance produced by the method. 3. Serialize the `PortablePdbBuilder` into a , and write the `Blob` into a PDB file stream (only if you're generating a standalone PDB). -4. Create a instance and add a (standalone PDB) or . +4. Create a instance and add a (standalone PDB) or . 5. Set the optional `debugDirectoryBuilder` argument when creating the instance. The following example shows how to emit symbol info and generate a PDB file. @@ -125,7 +125,7 @@ The following example shows how to read resources from the created assembly. :::code language="csharp" source="./snippets/System.Reflection.Emit/PersistedAssemblyBuilder/Overview/csharp/GenerateMetadataSnippets.cs" id="Snippet3"::: > [!NOTE] -> The metadata tokens for all members are populated on the operation. Don't use the tokens of a generated type and its members before saving, as they'll have default values or throw exceptions. It's safe to use tokens for types that are referenced, not generated. +> The metadata tokens for all members are populated on the operation. Don't use the tokens of a generated type and its members before saving, as they'll have default values or throw exceptions. It's safe to use tokens for types that are referenced, not generated. > > Some APIs that aren't important for emitting an assembly aren't implemented; for example, `GetCustomAttributes()` is not implemented. With the runtime implementation, you were able to use those APIs after creating the type. For the persisted `AssemblyBuilder`, they throw `NotSupportedException` or `NotImplementedException`. If you have a scenario that requires those APIs, file an issue in the [dotnet/runtime repo](https://github.com/dotnet/runtime). diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-typebuilder.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-typebuilder.md index 13064194c268f..df14a8f98480d 100644 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-typebuilder.md +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-typebuilder.md @@ -7,7 +7,7 @@ ms.date: 12/31/2023 [!INCLUDE [context](includes/context.md)] - is the root class used to control the creation of dynamic classes in the runtime. It provides a set of routines that are used to define classes, add methods and fields, and create the class inside a module. A new can be created from a dynamic module by calling the method, which returns a object. + is the root class used to control the creation of dynamic classes in the runtime. It provides a set of routines that are used to define classes, add methods and fields, and create the class inside a module. A new can be created from a dynamic module by calling the method, which returns a object. Reflection emit provides the following options for defining types: @@ -19,13 +19,13 @@ Reflection emit provides the following options for defining types: - Define a class with the given name, attributes, base class, and the class size as a whole. - Define a class with the given name, attributes, base class, packing size, and the class size as a whole. -To create an array type, pointer type, or byref type for an incomplete type that is represented by a object, use the method, method, or method, respectively. +To create an array type, pointer type, or byref type for an incomplete type that is represented by a object, use the method, method, or method, respectively. -Before a type is used, the method must be called. **CreateType** completes the creation of the type. Following the call to **CreateType**, the caller can instantiate the type by using the method, and invoke members of the type by using the method. It is an error to invoke methods that change the implementation of a type after **CreateType** has been called. For example, the common language runtime throws an exception if the caller tries to add new members to a type. +Before a type is used, the method must be called. **CreateType** completes the creation of the type. Following the call to **CreateType**, the caller can instantiate the type by using the method, and invoke members of the type by using the method. It is an error to invoke methods that change the implementation of a type after **CreateType** has been called. For example, the common language runtime throws an exception if the caller tries to add new members to a type. -A class initializer is created by using the method. **DefineTypeInitializer** returns a object. +A class initializer is created by using the method. **DefineTypeInitializer** returns a object. -Nested types are defined by calling one of the methods. +Nested types are defined by calling one of the methods. ## Attributes @@ -39,4 +39,4 @@ The class uses the is derived from , some of the abstract methods defined in the class are not fully implemented in the class. Calls to these methods throw a exception. The desired functionality can be obtained by retrieving the created type using the or and reflecting on the retrieved type. +- Although is derived from , some of the abstract methods defined in the class are not fully implemented in the class. Calls to these methods throw a exception. The desired functionality can be obtained by retrieving the created type using the or and reflecting on the retrieved type. diff --git a/docs/fundamentals/runtime-libraries/system-resources-missingmanifestresourceexception.md b/docs/fundamentals/runtime-libraries/system-resources-missingmanifestresourceexception.md index b0650f03024b7..6f430394e8c92 100644 --- a/docs/fundamentals/runtime-libraries/system-resources-missingmanifestresourceexception.md +++ b/docs/fundamentals/runtime-libraries/system-resources-missingmanifestresourceexception.md @@ -21,22 +21,22 @@ In .NET apps, is thrown The main causes of the exception include the following: -- The resource set is not identified by its fully qualified name. For example, if the `baseName` parameter in the call to the method specifies the root name of the resource set without a namespace, but the resource set is assigned a namespace when it is stored in its assembly, the call to the method throws this exception. +- The resource set is not identified by its fully qualified name. For example, if the `baseName` parameter in the call to the method specifies the root name of the resource set without a namespace, but the resource set is assigned a namespace when it is stored in its assembly, the call to the method throws this exception. If you've embedded the .resources file that contains the default culture's resources in your executable and your app is throwing a , you can use a reflection tool such as the [IL Disassembler (Ildasm.exe)](../../framework/tools/ildasm-exe-il-disassembler.md) to determine the fully qualified name of the resource. In ILDasm, double click the executable's **MANIFEST** label to open the **MANIFEST** window. Resources appear as `.mresource` items and are listed after external assembly references and custom assembly-level attributes. You can also compile the following simple utility, which lists the fully qualified names of embedded resources in the assembly whose name is passed to it as a command-line parameter. :::code language="csharp" source="./snippets/System.Resources/MissingManifestResourceException/Overview/csharp/resourcenames.cs" id="Snippet4"::: :::code language="vb" source="./snippets/System.Resources/ResourceManager/Overview/vb/resourcenames.vb" id="Snippet4"::: -- You identify the resource set by its resource file name (along with its optional namespace) and its file extension rather than by its namespace and root file name alone. For example, this exception is thrown if the neutral culture's resource set is named `GlobalResources` and you supply a value of `GlobalResources.resources` (instead of `GlobalResources`) to the `baseName` parameter of the constructor. +- You identify the resource set by its resource file name (along with its optional namespace) and its file extension rather than by its namespace and root file name alone. For example, this exception is thrown if the neutral culture's resource set is named `GlobalResources` and you supply a value of `GlobalResources.resources` (instead of `GlobalResources`) to the `baseName` parameter of the constructor. - The culture-specific resource set that is identified in a method call cannot be found, and the fallback resource set cannot be loaded. For example, if you create satellite assemblies for the English (United States) and Russia (Russian) cultures but you fail to provide a resource set for the neutral culture, this exception is thrown if your app's current culture is English (United Kingdom). uses the HRESULT `COR_E_MISSINGMANIFESTRESOURCE`, which has the value 0x80131532. - uses the default implementation, which supports reference equality. + uses the default implementation, which supports reference equality. -For a list of initial property values for an instance of , see the constructors. +For a list of initial property values for an instance of , see the constructors. > [!NOTE] > We recommend that you include a neutral set of resources in your main assembly, so your app won't fail if a satellite assembly is unavailable. diff --git a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-ctor.md b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-ctor.md index b10714840a551..c7e61cc4d45c0 100644 --- a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-ctor.md +++ b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-ctor.md @@ -88,7 +88,7 @@ This section pertains to the [!NOTE] -> To retrieve resources from *.resources* files directly instead of retrieving them from assemblies, you must call the method instead to instantiate a object. +> To retrieve resources from *.resources* files directly instead of retrieving them from assemblies, you must call the method instead to instantiate a object. If the resource file identified by `baseName` cannot be found in `assembly`, the method instantiates a object, but the attempt to retrieve a specific resource throws an exception, typically . For information about diagnosing the cause of the exception, see the "Handling the MissingManifestResourceException Exception" section of the class topic. @@ -120,4 +120,4 @@ It can be compiled by using the following command in C#: csc Example.cs /resource:ExampleResources.resources ``` -The example retrieves a reference to the assembly that contains the resource file by passing a type defined in that assembly to the `typeof` function (in C#) or the `GetType` function (in Visual Basic) and retrieving the value of its property. +The example retrieves a reference to the assembly that contains the resource file by passing a type defined in that assembly to the `typeof` function (in C#) or the `GetType` function (in Visual Basic) and retrieving the value of its property. diff --git a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getobject.md b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getobject.md index 916ab754abf7f..89c99fb9bca9e 100644 --- a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getobject.md +++ b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getobject.md @@ -10,7 +10,7 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The method is used to retrieve non-string resources. These include values that belong to primitive data types such as or , bitmaps (such as a object), or custom serialized objects. Typically, the returned object must be cast (in C#) or converted (in Visual Basic) to an object of the appropriate type. +The method is used to retrieve non-string resources. These include values that belong to primitive data types such as or , bitmaps (such as a object), or custom serialized objects. Typically, the returned object must be cast (in C#) or converted (in Visual Basic) to an object of the appropriate type. The property determines whether the comparison of `name` with the names of resources is case-insensitive or case-sensitive (the default). @@ -19,7 +19,7 @@ The property determines wheth ## method -The returned resource is localized for the UI culture of the current thread, which is defined by the property. If the resource is not localized for that culture, the resource manager uses fallback rules to load an appropriate resource. If no usable set of localized resources is found, the falls back on the default culture's resources. If a resource set for the default culture is not found, the method throws a exception or, if the resource set is expected to reside in a satellite assembly, a exception. If the resource manager can load an appropriate resource set but cannot find a resource named `name`, the method returns `null`. +The returned resource is localized for the UI culture of the current thread, which is defined by the property. If the resource is not localized for that culture, the resource manager uses fallback rules to load an appropriate resource. If no usable set of localized resources is found, the falls back on the default culture's resources. If a resource set for the default culture is not found, the method throws a exception or, if the resource set is expected to reside in a satellite assembly, a exception. If the resource manager can load an appropriate resource set but cannot find a resource named `name`, the method returns `null`. ### Example @@ -53,7 +53,7 @@ GetObject.exe ## method -The returned resource is localized for the culture that is specified by `culture`, or for the culture that is specified by the property if `culture` is `null`. If the resource is not localized for that culture, the resource manager uses fallback rules to load an appropriate resource. If no usable set of localized resources is found, the resource manager falls back on the default culture's resources. If a resource set for the default culture is not found, the method throws a exception or, if the resource set is expected to reside in a satellite assembly, a exception. If the resource manager can load an appropriate resource set but cannot find a resource named `name`, the method returns `null`. +The returned resource is localized for the culture that is specified by `culture`, or for the culture that is specified by the property if `culture` is `null`. If the resource is not localized for that culture, the resource manager uses fallback rules to load an appropriate resource. If no usable set of localized resources is found, the resource manager falls back on the default culture's resources. If a resource set for the default culture is not found, the method throws a exception or, if the resource set is expected to reside in a satellite assembly, a exception. If the resource manager can load an appropriate resource set but cannot find a resource named `name`, the method returns `null`. ### Example @@ -100,4 +100,4 @@ ShowNumbers.exe ## Performance considerations -If you call the method multiple times with the same `name` parameter, do not depend on the method returning a reference to the same object with each call. This is because the method can return a reference to an existing resource object in a cache, or it can reload the resource and return a reference to a new resource object. +If you call the method multiple times with the same `name` parameter, do not depend on the method returning a reference to the same object with each call. This is because the method can return a reference to an existing resource object in a cache, or it can reload the resource and return a reference to a new resource object. diff --git a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getstring.md b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getstring.md index b6aa0175b9328..08cb3a4f74f50 100644 --- a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getstring.md +++ b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getstring.md @@ -13,13 +13,13 @@ dev_langs: The property determines whether the comparison of `name` with the names of resources is case-insensitive (the default) or case-sensitive. > [!NOTE] -> The methods can throw more exceptions than are listed. One reason this might occur is if a method that this method calls throws an exception. For example, a exception might be thrown if an error was made deploying or installing a satellite assembly, or a exception might be thrown if a user-defined type throws a user-defined exception when the type is deserialized. +> The methods can throw more exceptions than are listed. One reason this might occur is if a method that this method calls throws an exception. For example, a exception might be thrown if an error was made deploying or installing a satellite assembly, or a exception might be thrown if a user-defined type throws a user-defined exception when the type is deserialized. ## method ### Desktop apps -In desktop apps, the resource that is returned is localized for the UI culture of the current thread, as defined by the property. If the resource has not been localized for that culture, the resource manager probes for a resource by following the steps outlined in the "Resource Fallback Process" section of the [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps) article. If no usable set of localized resources is found, the resource manager falls back on the default culture's resources. If the resource manager cannot load the default culture's resource set, the method throws a exception or, if the resource set is expected to reside in a satellite assembly, a exception. If the resource manager can load an appropriate resource set but cannot find a resource named `name`, the method returns `null`. +In desktop apps, the resource that is returned is localized for the UI culture of the current thread, as defined by the property. If the resource has not been localized for that culture, the resource manager probes for a resource by following the steps outlined in the "Resource Fallback Process" section of the [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps) article. If no usable set of localized resources is found, the resource manager falls back on the default culture's resources. If the resource manager cannot load the default culture's resource set, the method throws a exception or, if the resource set is expected to reside in a satellite assembly, a exception. If the resource manager can load an appropriate resource set but cannot find a resource named `name`, the method returns `null`. ### Windows 8.x apps @@ -30,7 +30,7 @@ In Windows 8.x apps, the method to retrieve culture-specific resources. It consists of resources compiled from .txt files for the English (en), French (France) (fr-FR), and Russian (Russia) (ru-RU) cultures. The example changes the current culture and current UI culture to English (United States), French (France), Russian (Russia), and Swedish (Sweden). It then calls the method to retrieve the localized string, which it displays along with the current day and month. Notice that the output displays the appropriate localized string except when the current UI culture is Swedish (Sweden). Because Swedish language resources are unavailable, the app instead uses the resources of the default culture, which is English. The example requires the text-based resource files listed in following table. Each has a single string resource named `DateStart`. +The following example uses the method to retrieve culture-specific resources. It consists of resources compiled from .txt files for the English (en), French (France) (fr-FR), and Russian (Russia) (ru-RU) cultures. The example changes the current culture and current UI culture to English (United States), French (France), Russian (Russia), and Swedish (Sweden). It then calls the method to retrieve the localized string, which it displays along with the current day and month. Notice that the output displays the appropriate localized string except when the current UI culture is Swedish (Sweden). Because Swedish language resources are unavailable, the app instead uses the resources of the default culture, which is English. The example requires the text-based resource files listed in following table. Each has a single string resource named `DateStart`. | Culture | File name | Resource name | Resource value | |---------|-----------------------|---------------|-----------------------| @@ -62,7 +62,7 @@ Here's the source code for the example (ShowDate.vb for the Visual Basic version ### Desktop apps -In desktop apps, if `culture` is `null`, the method uses the current UI culture obtained from the property. +In desktop apps, if `culture` is `null`, the method uses the current UI culture obtained from the property. The resource that is returned is localized for the culture specified by the `culture` parameter. If the resource has not been localized for `culture`, the resource manager probes for a resource by following the steps outlined in the "Resource Fallback Process" section of the [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps) topic. If no usable set of resources is found, the resource manager falls back on the default culture's resources. If the resource manager cannot load the default culture's resource set, the method throws a exception or, if the resource set is expected to reside in a satellite assembly, a exception. If the resource manager can load an appropriate resource set but cannot find a resource named `name`, the method returns `null`. @@ -75,7 +75,7 @@ In Windows 8.x apps, the method to retrieve culture-specific resources. The example's default culture is English (en), and it includes satellite assemblies for the French (France) (fr-FR) and Russian (Russia) (ru-RU) cultures. The example changes the current culture and current UI culture to Russian (Russia) before calling . It then calls the method and the method and passes objects that represent the French (France) and Swedish (Sweden) cultures to each method. In the output, the month and day of the month as well as the string that precedes them appear in French, because the method is able to retrieve the French language resource. However, when the Swedish (Sweden) culture is used, the month and day of the month appear in Swedish, although the string that precedes them is in English. This is because the resource manager cannot find localized Swedish language resources, so it returns a resource for the default English culture instead. +The following example uses the method to retrieve culture-specific resources. The example's default culture is English (en), and it includes satellite assemblies for the French (France) (fr-FR) and Russian (Russia) (ru-RU) cultures. The example changes the current culture and current UI culture to Russian (Russia) before calling . It then calls the method and the method and passes objects that represent the French (France) and Swedish (Sweden) cultures to each method. In the output, the month and day of the month as well as the string that precedes them appear in French, because the method is able to retrieve the French language resource. However, when the Swedish (Sweden) culture is used, the month and day of the month appear in Swedish, although the string that precedes them is in English. This is because the resource manager cannot find localized Swedish language resources, so it returns a resource for the default English culture instead. The example requires the text-based resource files listed in following table. Each has a single string resource named `DateStart`. diff --git a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md index 78a7e5451ca3d..07e7de5e10afd 100644 --- a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md +++ b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md @@ -17,10 +17,10 @@ The class retrieves resources from a bin ## Desktop apps -For desktop apps, the class retrieves resources from binary resource (.resources) files. Typically, a language compiler or the [Assembly Linker (AL.exe)](../../framework/tools/al-exe-assembly-linker.md) embeds these resource files in an assembly. You can also use a object to retrieve resources directly from a .resources file that is not embedded in an assembly, by calling the method. +For desktop apps, the class retrieves resources from binary resource (.resources) files. Typically, a language compiler or the [Assembly Linker (AL.exe)](../../framework/tools/al-exe-assembly-linker.md) embeds these resource files in an assembly. You can also use a object to retrieve resources directly from a .resources file that is not embedded in an assembly, by calling the method. > [!CAUTION] -> Using standalone .resources files in an ASP.NET app will break XCOPY deployment, because the resources remain locked until they are explicitly released by the method. If you want to deploy resources with your ASP.NET apps, you should compile your .resources files into satellite assemblies. +> Using standalone .resources files in an ASP.NET app will break XCOPY deployment, because the resources remain locked until they are explicitly released by the method. If you want to deploy resources with your ASP.NET apps, you should compile your .resources files into satellite assemblies. In a resource-based app, one .resources file contains the resources of the default culture whose resources are used if no culture-specific resources can be found. For example, if an app's default culture is English (en), the English language resources are used whenever localized resources cannot be found for a specific culture, such as English (United States) (en-US) or French (France) (fr-FR). Typically, the resources for the default culture are embedded in the main app assembly, and resources for other localized cultures are embedded in satellite assemblies. Satellite assemblies contain only resources. They have the same root file name as the main assembly and an extension of .resources.dll. For apps whose assemblies are not registered in the global assembly cache, satellite assemblies are stored in an app subdirectory whose name corresponds to the assembly's culture. @@ -42,12 +42,12 @@ You instantiate a object that retrieves The two most commonly called constructors are: -- looks up resources based on two pieces of information that you supply: the base name of the .resources file, and the assembly in which the default .resources file resides. The base name includes the namespace and root name of the .resources file, without its culture or extension. Note that .resources files that are compiled from the command line typically do not include a namespace name, whereas .resources files that are created in the Visual Studio environment do. For example, if a resource file is named MyCompany.StringResources.resources and the constructor is called from a static method named `Example.Main`, the following code instantiates a object that can retrieve resources from the .resources file: +- looks up resources based on two pieces of information that you supply: the base name of the .resources file, and the assembly in which the default .resources file resides. The base name includes the namespace and root name of the .resources file, without its culture or extension. Note that .resources files that are compiled from the command line typically do not include a namespace name, whereas .resources files that are created in the Visual Studio environment do. For example, if a resource file is named MyCompany.StringResources.resources and the constructor is called from a static method named `Example.Main`, the following code instantiates a object that can retrieve resources from the .resources file: :::code language="csharp" source="./snippets/System.Resources/ResourceManager/Overview/csharp/ctor1.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System.Resources/ResourceManager/Overview/vb/ctor1.vb" id="Snippet1"::: -- looks up resources in satellite assemblies based on information from a type object. The type's fully qualified name corresponds to the base name of the .resources file without its file name extension. In desktop apps that are created by using the Visual Studio Resource Designer, Visual Studio creates a wrapper class whose fully qualified name is the same as the root name of the .resources file. For example, if a resource file is named MyCompany.StringResources.resources and there is a wrapper class named `MyCompany.StringResources`, the following code instantiates a object that can retrieve resources from the .resources file: +- looks up resources in satellite assemblies based on information from a type object. The type's fully qualified name corresponds to the base name of the .resources file without its file name extension. In desktop apps that are created by using the Visual Studio Resource Designer, Visual Studio creates a wrapper class whose fully qualified name is the same as the root name of the .resources file. For example, if a resource file is named MyCompany.StringResources.resources and there is a wrapper class named `MyCompany.StringResources`, the following code instantiates a object that can retrieve resources from the .resources file: :::code language="csharp" source="./snippets/System.Resources/ResourceManager/Overview/csharp/ctor1.cs" id="Snippet2"::: :::code language="vb" source="./snippets/System.Resources/ResourceManager/Overview/vb/ctor1.vb" id="Snippet2"::: @@ -133,12 +133,12 @@ al /embed:Greetings.ru-RU.resources /culture:ru-RU /out:ru-RU\Example.resources. ### Retrieve resources -You call the and methods to access a specific resource. You can also call the method to retrieve non-string resources as a byte array. By default, in an app that has localized resources, these methods return the resource for the culture determined by the current UI culture of the thread that made the call. See the previous section, [ResourceManager and culture-specific resources](#resourcemanager-and-culture-specific-resources), for more information about how the current UI culture of a thread is defined. If the resource manager cannot find the resource for the current thread's UI culture, it uses a fallback process to retrieve the specified resource. If the resource manager cannot find any localized resources, it uses the resources of the default culture. For more information about resource fallback rules, see the "Resource Fallback Process" section of the article [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps). +You call the and methods to access a specific resource. You can also call the method to retrieve non-string resources as a byte array. By default, in an app that has localized resources, these methods return the resource for the culture determined by the current UI culture of the thread that made the call. See the previous section, [ResourceManager and culture-specific resources](#resourcemanager-and-culture-specific-resources), for more information about how the current UI culture of a thread is defined. If the resource manager cannot find the resource for the current thread's UI culture, it uses a fallback process to retrieve the specified resource. If the resource manager cannot find any localized resources, it uses the resources of the default culture. For more information about resource fallback rules, see the "Resource Fallback Process" section of the article [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps). > [!NOTE] > If the .resources file specified in the class constructor cannot be found, the attempt to retrieve a resource throws a or exception. For information about dealing with the exception, see the [Handle MissingManifestResourceException and MissingSatelliteAssemblyException Exceptions](#handle-missingmanifestresourceexception-and-missingsatelliteassemblyexception-exceptions) section later in this article. -The following example uses the method to retrieve culture-specific resources. It consists of resources compiled from .txt files for the English (en), French (France) (fr-FR), and Russian (Russia) (ru-RU) cultures. The example changes the current culture and current UI culture to English (United States), French (France), Russian (Russia), and Swedish (Sweden). It then calls the method to retrieve the localized string, which it displays along with the current day and month. Notice that the output displays the appropriate localized string except when the current UI culture is Swedish (Sweden). Because Swedish language resources are unavailable, the app instead uses the resources of the default culture, which is English. +The following example uses the method to retrieve culture-specific resources. It consists of resources compiled from .txt files for the English (en), French (France) (fr-FR), and Russian (Russia) (ru-RU) cultures. The example changes the current culture and current UI culture to English (United States), French (France), Russian (Russia), and Swedish (Sweden). It then calls the method to retrieve the localized string, which it displays along with the current day and month. Notice that the output displays the appropriate localized string except when the current UI culture is Swedish (Sweden). Because Swedish language resources are unavailable, the app instead uses the resources of the default culture, which is English. The example requires the text-based resource files listed in following table. Each has a single string resource named `DateStart`. @@ -170,12 +170,12 @@ al /out:ru-RU\Showdate.resources.dll /culture:ru-RU /embed:DateStrings.ru-RU.res There are two ways to retrieve the resources of a specific culture other than the current UI culture: -- You can call the , , or method to retrieve a resource for a specific culture. If a localized resource cannot be found, the resource manager uses the resource fallback process to locate an appropriate resource. -- You can call the method to obtain a object that represents the resources for a particular culture. In the method call, you can determine whether the resource manager probes for parent cultures if it is unable to find localized resources, or whether it simply falls back to the resources of the default culture. You can then use the methods to access the resources (localized for that culture) by name, or to enumerate the resources in the set. +- You can call the , , or method to retrieve a resource for a specific culture. If a localized resource cannot be found, the resource manager uses the resource fallback process to locate an appropriate resource. +- You can call the method to obtain a object that represents the resources for a particular culture. In the method call, you can determine whether the resource manager probes for parent cultures if it is unable to find localized resources, or whether it simply falls back to the resources of the default culture. You can then use the methods to access the resources (localized for that culture) by name, or to enumerate the resources in the set. ### Handle MissingManifestResourceException and MissingSatelliteAssemblyException exceptions -If you try to retrieve a specific resource, but the resource manager cannot find that resource and either no default culture has been defined or the resources of the default culture cannot be located, the resource manager throws a exception if it expects to find the resources in the main assembly or a if it expects to find the resources in a satellite assembly. Note that the exception is thrown when you call a resource retrieval method such as or , and not when you instantiate a object. +If you try to retrieve a specific resource, but the resource manager cannot find that resource and either no default culture has been defined or the resources of the default culture cannot be located, the resource manager throws a exception if it expects to find the resources in the main assembly or a if it expects to find the resources in a satellite assembly. Note that the exception is thrown when you call a resource retrieval method such as or , and not when you instantiate a object. The exception is typically thrown under the following conditions: @@ -183,7 +183,7 @@ The exception is typically thrown under the following conditions: - Your app doesn't have a default or neutral culture defined. Add the attribute to a source code file or to the project information file (AssemblyInfo.vb for a Visual Basic app or AssemblyInfo.cs for a C# app) file. -- The `baseName` parameter in the constructor does not specify the name of a .resources file. The name should include the resource file's fully qualified namespace but not its file name extension. Typically, resource files that are created in Visual Studio include namespace names, but resource files that are created and compiled at the command prompt do not. You can determine the names of embedded .resources files by compiling and running the following utility. This is a console app that accepts the name of a main assembly or satellite assembly as a command-line parameter. It displays the strings that should be provided as the `baseName` parameter so that the resource manager can correctly identify the resource. +- The `baseName` parameter in the constructor does not specify the name of a .resources file. The name should include the resource file's fully qualified namespace but not its file name extension. Typically, resource files that are created in Visual Studio include namespace names, but resource files that are created and compiled at the command prompt do not. You can determine the names of embedded .resources files by compiling and running the following utility. This is a console app that accepts the name of a main assembly or satellite assembly as a command-line parameter. It displays the strings that should be provided as the `baseName` parameter so that the resource manager can correctly identify the resource. :::code language="csharp" source="./snippets/System.Resources/MissingManifestResourceException/Overview/csharp/resourcenames.cs" id="Snippet4"::: :::code language="vb" source="./snippets/System.Resources/MissingManifestResourceException/Overview/vb/resourcenames.vb" id="Snippet4"::: @@ -246,7 +246,7 @@ For Windows 8.x apps, the class retrieve You can instantiate a object for a Windows 8.x app in the same way that you do for a desktop app. -You can then access the resources for a particular culture by passing the name of the resource to be retrieved to the method. By default, this method returns the resource for the culture determined by the current UI culture of the thread that made the call. You can also retrieve the resources for a specific culture by passing the name of the resource and a object that represents the culture whose resource is to be retrieved to the method. If the resource for the current UI culture or the specified culture cannot be found, the resource manager uses a UI language fallback list to locate a suitable resource. +You can then access the resources for a particular culture by passing the name of the resource to be retrieved to the method. By default, this method returns the resource for the culture determined by the current UI culture of the thread that made the call. You can also retrieve the resources for a specific culture by passing the name of the resource and a object that represents the culture whose resource is to be retrieved to the method. If the resource for the current UI culture or the specified culture cannot be found, the resource manager uses a UI language fallback list to locate a suitable resource. ## Examples diff --git a/docs/fundamentals/runtime-libraries/system-resources-resourcereader.md b/docs/fundamentals/runtime-libraries/system-resources-resourcereader.md index 9d0cf47dceda7..103a44e3f3498 100644 --- a/docs/fundamentals/runtime-libraries/system-resources-resourcereader.md +++ b/docs/fundamentals/runtime-libraries/system-resources-resourcereader.md @@ -15,7 +15,7 @@ dev_langs: The class provides a standard implementation of the interface. A instance represents either a standalone .resources file or a .resources file that is embedded in an assembly. It is used to enumerate the resources in a .resources file and retrieve its name/value pairs. It differs from the class, which is used to retrieve specified named resources from a .resources file that is embedded in an assembly. The class is used to retrieve resources whose names are known in advance, whereas the class is useful for retrieving resources whose number or precise names are not known at compile time. For example, an application may use a resources file to store configuration information that is organized into sections and items in a section, where the number of sections or items in a section is not known in advance. Resources can then be named generically (such as `Section1`, `Section1Item1`, `Section1Item2`, and so on) and retrieved by using a object. > [!IMPORTANT] -> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface documentation. +> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface documentation. ## Instantiate a ResourceReader object @@ -26,29 +26,29 @@ To instantiate a object that reads from a :::code language="csharp" source="./snippets/System.Resources/ResourceReader/Overview/csharp/ctor1.cs" id="Snippet2"::: :::code language="vb" source="./snippets/System.Resources/ResourceReader/Overview/vb/ctor1.vb" id="Snippet2"::: -To create a object that represents an embedded .resources file, instantiate an object from the assembly in which the .resources file is embedded. Its method returns a object that can be passed to the constructor. The following example instantiates a object that represents an embedded .resources file. +To create a object that represents an embedded .resources file, instantiate an object from the assembly in which the .resources file is embedded. Its method returns a object that can be passed to the constructor. The following example instantiates a object that represents an embedded .resources file. :::code language="csharp" source="./snippets/System.Resources/ResourceReader/Overview/csharp/ctor1.cs" id="Snippet3"::: :::code language="vb" source="./snippets/System.Resources/ResourceReader/Overview/vb/ctor1.vb" id="Snippet3"::: ## Enumerate a ResourceReader object's resources -To enumerate the resources in a .resources file, you call the method, which returns an object. You call the `IDictionaryEnumerator.MoveNext` method to move from one resource to the next. The method returns `false` when all the resources in the .resources file have been enumerated. +To enumerate the resources in a .resources file, you call the method, which returns an object. You call the `IDictionaryEnumerator.MoveNext` method to move from one resource to the next. The method returns `false` when all the resources in the .resources file have been enumerated. > [!NOTE] -> Although the class implements the interface and the method, the method does not provide the implementation. Instead, the method returns an interface object that provides access to each resource's name/value pair. +> Although the class implements the interface and the method, the method does not provide the implementation. Instead, the method returns an interface object that provides access to each resource's name/value pair. You can retrieve the individual resources in the collection in two ways: - You can iterate each resource in the collection and use properties to retrieve the resource name and value. We recommend this technique when all the resources are of the same type, or you know the data type of each resource. -- You can retrieve the name of each resource when you iterate the collection and call the method to retrieve the resource's data. We recommend this approach when you do not know the data type of each resource or if the previous approach throws exceptions. +- You can retrieve the name of each resource when you iterate the collection and call the method to retrieve the resource's data. We recommend this approach when you do not know the data type of each resource or if the previous approach throws exceptions. ### Retrieve resources by using IDictionaryEnumerator properties The first method of enumerating the resources in a .resources file involves directly retrieving each resource's name/value pair. After you call the `IDictionaryEnumerator.MoveNext` method to move to each resource in the collection, you can retrieve the resource name from the property and the resource data from the property. -The following example shows how to retrieve the name and value of each resource in a .resources file by using the and properties. To run the example, create the following text file named ApplicationResources.txt to define string resources. +The following example shows how to retrieve the name and value of each resource in a .resources file by using the and properties. To run the example, create the following text file named ApplicationResources.txt to define string resources. ``` Title="Contact Information" @@ -84,13 +84,13 @@ The attempt to retrieve resource data from the if the assembly that contains the type to which the data belongs cannot be found. - A if the type to which the data belongs cannot be cannot be found. -Typically, these exceptions are thrown if the .resources file has been modified manually, if the assembly in which a type is defined has either not been included with an application or has been inadvertently deleted, or if the assembly is an older version that predates a type. If one of these exceptions is thrown, you can retrieve resources by enumerating each resource and calling the method, as the following section shows. This approach provides you with some information about the data type that the property attempted to return. +Typically, these exceptions are thrown if the .resources file has been modified manually, if the assembly in which a type is defined has either not been included with an application or has been inadvertently deleted, or if the assembly is an older version that predates a type. If one of these exceptions is thrown, you can retrieve resources by enumerating each resource and calling the method, as the following section shows. This approach provides you with some information about the data type that the property attempted to return. ### Retrieve resources by name with GetResourceData -The second approach to enumerating resources in a .resources file also involves navigating through the resources in the file by calling the `IDictionaryEnumerator.MoveNext` method. For each resource, you retrieve the resource's name from the property, which is then passed to the method to retrieve the resource's data. This is returned as a byte array in the `resourceData` argument. +The second approach to enumerating resources in a .resources file also involves navigating through the resources in the file by calling the `IDictionaryEnumerator.MoveNext` method. For each resource, you retrieve the resource's name from the property, which is then passed to the method to retrieve the resource's data. This is returned as a byte array in the `resourceData` argument. -This approach is more awkward than retrieving the resource name and value from the and properties, because it returns the actual bytes that form the resource value. However, if the attempt to retrieve the resource throws an exception, the method can help identify the source of the exception by supplying information about the resource's data type. For more information about the string that indicates the resource's data type, see . +This approach is more awkward than retrieving the resource name and value from the and properties, because it returns the actual bytes that form the resource value. However, if the attempt to retrieve the resource throws an exception, the method can help identify the source of the exception by supplying information about the resource's data type. For more information about the string that indicates the resource's data type, see . The following example illustrates how to use this approach to retrieve resources and to handle any exceptions that are thrown. It programmatically creates a binary .resources file that contains four strings, one Boolean, one integer, and one bitmap. To run the example, do the following: @@ -108,4 +108,4 @@ The following example illustrates how to use this approach to retrieve resources :::code language="csharp" source="./snippets/System.Resources/ResourceReader/Overview/csharp/readresourceex1.cs" id="Snippet6"::: - After modifying the source code (for example, by deliberately throwing a at the end of the `try` block), you can run the example to see how calls to enable you to retrieve or recreate some resource information. + After modifying the source code (for example, by deliberately throwing a at the end of the `try` block), you can run the example to see how calls to enable you to retrieve or recreate some resource information. diff --git a/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-internalsvisibletoattribute.md b/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-internalsvisibletoattribute.md index 4ccd178cdb28d..cc8d73a064ab9 100644 --- a/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-internalsvisibletoattribute.md +++ b/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-internalsvisibletoattribute.md @@ -29,13 +29,13 @@ They can also appear with separate constructor. Both the current assembly and the friend assembly must be unsigned, or both assemblies must be signed with a strong name. +The friend assembly is identified by the constructor. Both the current assembly and the friend assembly must be unsigned, or both assemblies must be signed with a strong name. If both assemblies are unsigned, the `assemblyName` argument consists of the name of the friend assembly, specified without a directory path or file name extension. -If both assemblies are signed with a strong name, the argument to the constructor must consist of the name of the assembly without its directory path or file name extension, along with the full public key (and not its public key token). To get the full public key of a strong-named assembly, see the [Get the full public key](#get-the-full-public-key) section later in this article. For more information about using with strong-named assemblies, see the constructor. +If both assemblies are signed with a strong name, the argument to the constructor must consist of the name of the assembly without its directory path or file name extension, along with the full public key (and not its public key token). To get the full public key of a strong-named assembly, see the [Get the full public key](#get-the-full-public-key) section later in this article. For more information about using with strong-named assemblies, see the constructor. -Do not include values for the , , or field in the argument; the Visual Basic, C#, and C++ compilers treat this as a compiler error. If you use a compiler that does not treat it as an error (such as the [IL Assembler (ILAsm.exe)](../../framework/tools/ilasm-exe-il-assembler.md)) and the assemblies are strong-named, a exception is thrown the first time the specified friend assembly accesses the assembly that contains the attribute. +Do not include values for the , , or field in the argument; the Visual Basic, C#, and C++ compilers treat this as a compiler error. If you use a compiler that does not treat it as an error (such as the [IL Assembler (ILAsm.exe)](../../framework/tools/ilasm-exe-il-assembler.md)) and the assemblies are strong-named, a exception is thrown the first time the specified friend assembly accesses the assembly that contains the attribute. For more information about how to use this attribute, see [Friend assemblies](../../standard/assembly/friend.md) and [C++ friend assemblies](/cpp/dotnet/friend-assemblies-cpp). diff --git a/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-runtimehelpers-gethashcode.md b/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-runtimehelpers-gethashcode.md index 678307d01aa39..b540172fade10 100644 --- a/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-runtimehelpers-gethashcode.md +++ b/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-runtimehelpers-gethashcode.md @@ -10,40 +10,40 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The method always calls the method non-virtually, even if the object's type has overridden the method. Therefore, using might differ from calling `GetHashCode` directly on the object with the method. +The method always calls the method non-virtually, even if the object's type has overridden the method. Therefore, using might differ from calling `GetHashCode` directly on the object with the method. > [!WARNING] -> Although the method returns identical hash codes for identical object references, you should not use this method to test for object identity, because this hash code does not uniquely identify an object reference. To test for object identity (that is, to test that two objects reference the same object in memory), call the method. Nor should you use to test whether two strings represent equal object references, because the string is interned. To test for string interning, call the method. +> Although the method returns identical hash codes for identical object references, you should not use this method to test for object identity, because this hash code does not uniquely identify an object reference. To test for object identity (that is, to test that two objects reference the same object in memory), call the method. Nor should you use to test whether two strings represent equal object references, because the string is interned. To test for string interning, call the method. -The and methods differ as follows: +The and methods differ as follows: -- returns a hash code that is based on the object's definition of equality. For example, two strings with identical contents will return the same value for . -- returns a hash code that indicates object identity. That is, two string variables whose contents are identical and that represent a string that is interned (see the [String Interning](#string-interning) section) or that represent a single string in memory return identical hash codes. +- returns a hash code that is based on the object's definition of equality. For example, two strings with identical contents will return the same value for . +- returns a hash code that indicates object identity. That is, two string variables whose contents are identical and that represent a string that is interned (see the [String Interning](#string-interning) section) or that represent a single string in memory return identical hash codes. > [!IMPORTANT] -> Note that always returns identical hash codes for equal object references. However, the reverse is not true: equal hash codes do not indicate equal object references. A particular hash code value is not unique to a particular object reference; different object references can generate identical hash codes. +> Note that always returns identical hash codes for equal object references. However, the reverse is not true: equal hash codes do not indicate equal object references. A particular hash code value is not unique to a particular object reference; different object references can generate identical hash codes. This method is used by compilers. ## String interning -The common language runtime (CLR) maintains an internal pool of strings and stores literals in the pool. If two strings (for example, `str1` and `str2`) are formed from an identical string literal, the CLR will set `str1` and `str2` to point to the same location on the managed heap to conserve memory. Calling on these two string objects will produce the same hash code, contrary to the second bulleted item in the previous section. +The common language runtime (CLR) maintains an internal pool of strings and stores literals in the pool. If two strings (for example, `str1` and `str2`) are formed from an identical string literal, the CLR will set `str1` and `str2` to point to the same location on the managed heap to conserve memory. Calling on these two string objects will produce the same hash code, contrary to the second bulleted item in the previous section. -The CLR adds only literals to the pool. Results of string operations such as concatenation are not added to the pool, unless the compiler resolves the string concatenation as a single string literal. Therefore, if `str2` was created as the result of a concatenation operation, and `str2` is identical to `str1`, using on these two string objects will not produce the same hash code. +The CLR adds only literals to the pool. Results of string operations such as concatenation are not added to the pool, unless the compiler resolves the string concatenation as a single string literal. Therefore, if `str2` was created as the result of a concatenation operation, and `str2` is identical to `str1`, using on these two string objects will not produce the same hash code. -If you want to add a concatenated string to the pool explicitly, use the method. +If you want to add a concatenated string to the pool explicitly, use the method. -You can also use the method to check whether a string has an interned reference. +You can also use the method to check whether a string has an interned reference. ## Examples -The following example demonstrates the difference between the and methods. The output from the example illustrates the following: +The following example demonstrates the difference between the and methods. The output from the example illustrates the following: - Both sets of hash codes for the first set of strings passed to the `ShowHashCodes` method are different, because the strings are completely different. -- generates the same hash code for the second set of strings passed to the `ShowHashCodes` method, because the strings are equal. However, the method does not. The first string is defined by using a string literal and so is interned. Although the value of the second string is the same, it is not interned, because it is returned by a call to the method. +- generates the same hash code for the second set of strings passed to the `ShowHashCodes` method, because the strings are equal. However, the method does not. The first string is defined by using a string literal and so is interned. Although the value of the second string is the same, it is not interned, because it is returned by a call to the method. -- In the case of the third string, the hash codes produced by for both strings are identical, as are the hash codes produced by . This is because the compiler has treated the value assigned to both strings as a single string literal, and so the string variables refer to the same interned string. +- In the case of the third string, the hash codes produced by for both strings are identical, as are the hash codes produced by . This is because the compiler has treated the value assigned to both strings as a single string literal, and so the string variables refer to the same interned string. :::code language="csharp" source="./snippets/System.Runtime.CompilerServices/RuntimeHelpers/GetHashCode/csharp/gethashcodeex1.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System.Runtime.CompilerServices/RuntimeHelpers/GetHashCode/vb/gethashcodeex1.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-icustommarshaler.md b/docs/fundamentals/runtime-libraries/system-runtime-interopservices-icustommarshaler.md index b2b8ff0e2051d..825f99d938bb5 100644 --- a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-icustommarshaler.md +++ b/docs/fundamentals/runtime-libraries/system-runtime-interopservices-icustommarshaler.md @@ -65,35 +65,35 @@ The interface includes me |Type of operation|ICustomMarshaler method|Description| |-----------------------|-----------------------------|-----------------| -|Conversion (from native to managed code)||Marshals a pointer to native data into a managed object. This method returns a custom runtime callable wrapper (RCW) that can marshal the unmanaged interface that is passed as an argument. The marshaller should return an instance of the custom RCW for that type.| -|Conversion (from managed to native code)||Marshals a managed object into a pointer to native data. This method returns a custom COM callable wrapper (CCW) that can marshal the managed interface that is passed as an argument. The marshaller should return an instance of the custom CCW for that type.| -|Cleanup (of native code)||Enables the marshaller to clean up the native data (the CCW) that is returned by the method.| -|Cleanup (of managed code)||Enables the marshaller to clean up the managed data (the RCW) that is returned by the method.| -|Information (about native code)||Returns the size of the unmanaged data to be marshaled.| +|Conversion (from native to managed code)||Marshals a pointer to native data into a managed object. This method returns a custom runtime callable wrapper (RCW) that can marshal the unmanaged interface that is passed as an argument. The marshaller should return an instance of the custom RCW for that type.| +|Conversion (from managed to native code)||Marshals a managed object into a pointer to native data. This method returns a custom COM callable wrapper (CCW) that can marshal the managed interface that is passed as an argument. The marshaller should return an instance of the custom CCW for that type.| +|Cleanup (of native code)||Enables the marshaller to clean up the native data (the CCW) that is returned by the method.| +|Cleanup (of managed code)||Enables the marshaller to clean up the managed data (the RCW) that is returned by the method.| +|Information (about native code)||Returns the size of the unmanaged data to be marshaled.| ### Conversion - + Marshals a pointer to native data into a managed object. This method returns a custom runtime callable wrapper (RCW) that can marshal the unmanaged interface that is passed as an argument. The marshaller should return an instance of the custom RCW for that type. - + Marshals a managed object into a pointer to native data. This method returns a custom COM callable wrapper (CCW) that can marshal the managed interface that is passed as an argument. The marshaller should return an instance of the custom CCW for that type. ### Cleanup - + -Enables the marshaller to clean up the native data (the CCW) that is returned by the method. +Enables the marshaller to clean up the native data (the CCW) that is returned by the method. - + -Enables the marshaller to clean up the managed data (the RCW) that is returned by the method. +Enables the marshaller to clean up the managed data (the RCW) that is returned by the method. ### Size information - + Returns the size of the unmanaged data to be marshaled. @@ -121,7 +121,7 @@ You must also pass the attribute identifies the custom marshaller so it can activate the appropriate wrapper. The common language runtime's interop service then examines the attribute and creates the custom marshaller the first time the argument (parameter or field) needs to be marshaled. -The runtime then calls the and methods on the custom marshaller to activate the correct wrapper to handle the call. +The runtime then calls the and methods on the custom marshaller to activate the correct wrapper to handle the call. ## Use a custom marshaller diff --git a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-marshal-getactiveobject.md b/docs/fundamentals/runtime-libraries/system-runtime-interopservices-marshal-getactiveobject.md index 7d738ef0d797f..376e5d0e5012c 100644 --- a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-marshal-getactiveobject.md +++ b/docs/fundamentals/runtime-libraries/system-runtime-interopservices-marshal-getactiveobject.md @@ -7,7 +7,7 @@ ms.date: 01/24/2024 [!INCLUDE [context](includes/context.md)] - exposes the COM [GetActiveObject](/windows/win32/api/oleauto/nf-oleauto-getactiveobject) function from OLEAUT32.DLL; however, the latter expects a class identifier (CLSID) instead of the programmatic identifier (`ProgID`) expected by this method. To obtain a running instance of a COM object without a registered `ProgID`, use platform invoke to define the COM [GetActiveObject](/windows/win32/api/oleauto/nf-oleauto-getactiveobject) function. For a description of platform invoke, see [Consuming Unmanaged DLL Functions](../../framework/interop/consuming-unmanaged-dll-functions.md). + exposes the COM [GetActiveObject](/windows/win32/api/oleauto/nf-oleauto-getactiveobject) function from OLEAUT32.DLL; however, the latter expects a class identifier (CLSID) instead of the programmatic identifier (`ProgID`) expected by this method. To obtain a running instance of a COM object without a registered `ProgID`, use platform invoke to define the COM [GetActiveObject](/windows/win32/api/oleauto/nf-oleauto-getactiveobject) function. For a description of platform invoke, see [Consuming Unmanaged DLL Functions](../../framework/interop/consuming-unmanaged-dll-functions.md). ## ProgID and CLSID diff --git a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-safehandle.md b/docs/fundamentals/runtime-libraries/system-runtime-interopservices-safehandle.md index 257daf18eac44..98156b79914ec 100644 --- a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-safehandle.md +++ b/docs/fundamentals/runtime-libraries/system-runtime-interopservices-safehandle.md @@ -11,7 +11,7 @@ The class provides critical fin ## Why SafeHandle? -Although overrides to the method allow cleanup of unmanaged resources when an object is being garbage collected, in some circumstances, finalizable objects can be reclaimed by garbage collection while executing a method within a platform invoke call. If a finalizer frees the handle passed to that platform invoke call, it could lead to handle corruption. The handle could also be reclaimed while your method is blocked during a platform invoke call, such as while reading a file. +Although overrides to the method allow cleanup of unmanaged resources when an object is being garbage collected, in some circumstances, finalizable objects can be reclaimed by garbage collection while executing a method within a platform invoke call. If a finalizer frees the handle passed to that platform invoke call, it could lead to handle corruption. The handle could also be reclaimed while your method is blocked during a platform invoke call, such as while reading a file. More critically, because Windows aggressively recycles handles, a handle could be recycled and point to another resource that might contain sensitive data. This is known as a recycle attack and can potentially corrupt data and be a security threat. diff --git a/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractattribute.md b/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractattribute.md index aed56ce7b438f..f557d15c4412b 100644 --- a/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractattribute.md +++ b/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractattribute.md @@ -33,7 +33,7 @@ You can also run the tool against an endpoint that returns a Web Services Descri ## Reuse existing types -A data contract has two basic requirements: a stable name and a list of members. The stable name consists of the namespace uniform resource identifier (URI) and the local name of the contract. By default, when you apply the to a class, it uses the class name as the local name and the class's namespace (prefixed with `"http://schemas.datacontract.org/2004/07/"`) as the namespace URI. You can override the defaults by setting the and properties. You can also change the namespace by applying the to the namespace. Use this capability when you have an existing type that processes data exactly as you require but has a different namespace and class name from the data contract. By overriding the default values, you can reuse your existing type and have the serialized data conform to the data contract. +A data contract has two basic requirements: a stable name and a list of members. The stable name consists of the namespace uniform resource identifier (URI) and the local name of the contract. By default, when you apply the to a class, it uses the class name as the local name and the class's namespace (prefixed with `"http://schemas.datacontract.org/2004/07/"`) as the namespace URI. You can override the defaults by setting the and properties. You can also change the namespace by applying the to the namespace. Use this capability when you have an existing type that processes data exactly as you require but has a different namespace and class name from the data contract. By overriding the default values, you can reuse your existing type and have the serialized data conform to the data contract. > [!NOTE] > In any code, you can use the word `DataContract` instead of the longer . diff --git a/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractserializer.md b/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractserializer.md index e5a1cf3f6b3fa..b0d654dd5cec3 100644 --- a/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractserializer.md +++ b/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractserializer.md @@ -11,7 +11,7 @@ Use the class to seri For a list of types that can be serialized, see [Types Supported by the Data Contract Serializer](../../framework/wcf/feature-details/types-supported-by-the-data-contract-serializer.md). -To use the , first create an instance of a class and an object appropriate to writing or reading the format; for example, an instance of the . Then call the method to persist the data. To retrieve data, create an object appropriate to reading the data format (such as an for an XML document) and call the method. +To use the , first create an instance of a class and an object appropriate to writing or reading the format; for example, an instance of the . Then call the method to persist the data. To retrieve data, create an object appropriate to reading the data format (such as an for an XML document) and call the method. For more information about using the , see [Serialization and Deserialization](../../framework/wcf/feature-details/serialization-and-deserialization.md). @@ -32,7 +32,7 @@ If you are creating a class that has fields or properties that must be populated ## Add to the collection of known types -When serializing or deserializing an object, it is required that the type is "known" to the . Begin by creating an instance of a class that implements (such as ) and adding the known types to the collection. Then create an instance of the using one of the overloads that takes the (for example, ). +When serializing or deserializing an object, it is required that the type is "known" to the . Begin by creating an instance of a class that implements (such as ) and adding the known types to the collection. Then create an instance of the using one of the overloads that takes the (for example, ). > [!NOTE] > Unlike other primitive types, the structure is not a known type by default, so it must be manually added to the list of known types (see [Data Contract Known Types](../../framework/wcf/feature-details/data-contract-known-types.md)). diff --git a/docs/fundamentals/runtime-libraries/system-runtime-serialization-iextensibledataobject.md b/docs/fundamentals/runtime-libraries/system-runtime-serialization-iextensibledataobject.md index b2bd9d383d864..e8421c942b836 100644 --- a/docs/fundamentals/runtime-libraries/system-runtime-serialization-iextensibledataobject.md +++ b/docs/fundamentals/runtime-libraries/system-runtime-serialization-iextensibledataobject.md @@ -19,6 +19,6 @@ The interface provides 4. Implement get and set methods for the property using the new private member. -5. Apply the attribute to the class. Set the and properties to appropriate values if necessary. +5. Apply the attribute to the class. Set the and properties to appropriate values if necessary. For more information about versioning of types, see [Data Contract Versioning](../../framework/wcf/feature-details/data-contract-versioning.md). For information about creating forward-compatible data contracts, see [Forward-Compatible Data Contracts](../../framework/wcf/feature-details/forward-compatible-data-contracts.md). For more information about data contracts, see [Using Data Contracts](../../framework/wcf/feature-details/using-data-contracts.md). diff --git a/docs/fundamentals/runtime-libraries/system-runtime-serialization-xsddatacontractexporter.md b/docs/fundamentals/runtime-libraries/system-runtime-serialization-xsddatacontractexporter.md index e7feb443c4a5c..6af813e2f918b 100644 --- a/docs/fundamentals/runtime-libraries/system-runtime-serialization-xsddatacontractexporter.md +++ b/docs/fundamentals/runtime-libraries/system-runtime-serialization-xsddatacontractexporter.md @@ -20,14 +20,14 @@ The generates an class that contains XML schema files, you should be aware of the following. -The set of types you are exporting are recorded as an internal set of data contracts. Thus, you can call the method multiple times to add new types to the schema set without degrading performance because only the new types will be added to the set. During the operation, the existing schemas are compared to the new schemas being added. If there are conflicts, an exception will be thrown. A conflict is usually detected if two types with the same data contract name but different contracts (different members) are exported by the same instance. +The set of types you are exporting are recorded as an internal set of data contracts. Thus, you can call the method multiple times to add new types to the schema set without degrading performance because only the new types will be added to the set. During the operation, the existing schemas are compared to the new schemas being added. If there are conflicts, an exception will be thrown. A conflict is usually detected if two types with the same data contract name but different contracts (different members) are exported by the same instance. ## Use the exporter A recommended way of using this class is as follows: -1. Use one of the overloads to determine whether the specified type or set of types can be exported. Use one of the overloads that is appropriate to your requirements. +1. Use one of the overloads to determine whether the specified type or set of types can be exported. Use one of the overloads that is appropriate to your requirements. -2. Call the corresponding method. +2. Call the corresponding method. 3. Retrieve the schemas from the property. diff --git a/docs/fundamentals/runtime-libraries/system-runtime-versioning-componentguaranteesattribute.md b/docs/fundamentals/runtime-libraries/system-runtime-versioning-componentguaranteesattribute.md index 1f0ef934f6e14..8602bb9d308d8 100644 --- a/docs/fundamentals/runtime-libraries/system-runtime-versioning-componentguaranteesattribute.md +++ b/docs/fundamentals/runtime-libraries/system-runtime-versioning-componentguaranteesattribute.md @@ -90,7 +90,7 @@ The following are considered breaking changes and are not allowed for primitive After a component, type, or member is marked with the guarantee, it cannot be changed to either or . -Typically, exchange types are the basic types (such as and in .NET) and interfaces (such as , , and ) that are commonly used in public interfaces. +Typically, exchange types are the basic types (such as and in .NET) and interfaces (such as , , and ) that are commonly used in public interfaces. Exchange types may publicly expose only other types that are also marked with compatibility. In addition, exchange types cannot depend on the behavior of Windows APIs that are prone to change. diff --git a/docs/fundamentals/runtime-libraries/system-security-cryptography-rsacryptoserviceprovider.md b/docs/fundamentals/runtime-libraries/system-security-cryptography-rsacryptoserviceprovider.md index 730f08d5fd3f7..78aa267d49e79 100644 --- a/docs/fundamentals/runtime-libraries/system-security-cryptography-rsacryptoserviceprovider.md +++ b/docs/fundamentals/runtime-libraries/system-security-cryptography-rsacryptoserviceprovider.md @@ -19,4 +19,4 @@ Unlike the RSA implementation in unmanaged CAPI, the class throws a . -To interoperate with CAPI, you must manually reverse the order of encrypted bytes before the encrypted data interoperates with another API. You can easily reverse the order of a managed byte array by calling the method. +To interoperate with CAPI, you must manually reverse the order of encrypted bytes before the encrypted data interoperates with another API. You can easily reverse the order of a managed byte array by calling the method. diff --git a/docs/fundamentals/runtime-libraries/system-security-cryptography-rsaparameters.md b/docs/fundamentals/runtime-libraries/system-security-cryptography-rsaparameters.md index 3b7575f717752..51537ab892289 100644 --- a/docs/fundamentals/runtime-libraries/system-security-cryptography-rsaparameters.md +++ b/docs/fundamentals/runtime-libraries/system-security-cryptography-rsaparameters.md @@ -9,7 +9,7 @@ ms.date: 12/31/2023 The structure represents the standard parameters for the RSA algorithm. -The class exposes an method that enables you to retrieve the raw RSA key in the form of an structure. +The class exposes an method that enables you to retrieve the raw RSA key in the form of an structure. To understand the contents of this structure, it helps to be familiar with how the algorithm works. The next section discusses the algorithm briefly. @@ -42,6 +42,6 @@ The following table summarizes the fields of the | p | prime1 | | | q | prime2 | -The security of RSA derives from the fact that, given the public key { e, n }, it is computationally infeasible to calculate d, either directly or by factoring n into p and q. Therefore, any part of the key related to d, p, or q must be kept secret. If you call and ask for only the public key information, this is why you will receive only and . The other fields are available only if you have access to the private key, and you request it. +The security of RSA derives from the fact that, given the public key { e, n }, it is computationally infeasible to calculate d, either directly or by factoring n into p and q. Therefore, any part of the key related to d, p, or q must be kept secret. If you call and ask for only the public key information, this is why you will receive only and . The other fields are available only if you have access to the private key, and you request it. is not encrypted in any way, so you must be careful when you use it with the private key information. All members of are serialized. If anyone can derive or intercept the private key parameters, the key and all the information encrypted or signed with it are compromised. diff --git a/docs/fundamentals/runtime-libraries/system-security-cryptography-xml-signedxml.md b/docs/fundamentals/runtime-libraries/system-security-cryptography-xml-signedxml.md index 9958fc26dfb50..3496203e42085 100644 --- a/docs/fundamentals/runtime-libraries/system-security-cryptography-xml-signedxml.md +++ b/docs/fundamentals/runtime-libraries/system-security-cryptography-xml-signedxml.md @@ -88,10 +88,10 @@ The main parts of this structure are: Unless interoperating with a specification which requires the use of a different value, we recommend that you use the default .NET canonicalization method, which is the XML-C14N 1.0 algorithm, whose value is . The XML-C14N 1.0 algorithm is required to be supported by all implementations of XMLDSIG, particularly as it is an implicit final transform to apply. -There are versions of canonicalization algorithms which support preserving comments. Comment-preserving canonicalization methods are not recommended because they violate the "sign what is seen" principle. That is, the comments in a `` element will not alter the processing logic for how the signature is performed, merely what the signature value is. When combined with a weak signature algorithm, allowing the comments to be included gives an attacker unnecessary freedom to force a hash collision, making a tampered document appear legitimate. In .NET Framework, only built-in canonicalizers are supported by default. To support additional or custom canonicalizers, see the property. If the document uses a canonicalization method that is not in the collection represented by the property, then the method will return `false`. +There are versions of canonicalization algorithms which support preserving comments. Comment-preserving canonicalization methods are not recommended because they violate the "sign what is seen" principle. That is, the comments in a `` element will not alter the processing logic for how the signature is performed, merely what the signature value is. When combined with a weak signature algorithm, allowing the comments to be included gives an attacker unnecessary freedom to force a hash collision, making a tampered document appear legitimate. In .NET Framework, only built-in canonicalizers are supported by default. To support additional or custom canonicalizers, see the property. If the document uses a canonicalization method that is not in the collection represented by the property, then the method will return `false`. > [!NOTE] -> An extremely defensive application can remove any values it does not expect signers to use from the collection. +> An extremely defensive application can remove any values it does not expect signers to use from the collection. ## Are the reference values safe from tampering? @@ -105,15 +105,15 @@ It is very common to see `URI` values in the form of anchors such as #foo, refer If your application considers comments to be semantic (which is not common when dealing with XML), then you should use "#xpointer(/)" instead of "", and "#xpointer(id('foo'))" instead of "#foo". The #xpointer versions are interpreted as including comments, while the shortname forms are excluding comments. -If you need to accept documents which are only partially protected and you want to ensure that you are reading the same content that the signature protected, use the method. +If you need to accept documents which are only partially protected and you want to ensure that you are reading the same content that the signature protected, use the method. ## Security considerations about the KeyInfo element The data in the optional `` element (that is, the property), which contains a key to validate the signature, should not be trusted. -In particular, when the value represents a bare RSA, DSA or ECDSA public key, the document could have been tampered with, despite the method reporting that the signature is valid. This can happen because the entity doing the tampering just has to generate a new key and re-sign the tampered document with that new key. So, unless your application verifies that the public key is an expected value, the document should be treated as if it were tampered with. This requires that your application examine the public key embedded within the document and verify it against a list of known values for the document context. For example, if the document could be understood to be issued by a known user, you'd check the key against a list of known keys used by that user. +In particular, when the value represents a bare RSA, DSA or ECDSA public key, the document could have been tampered with, despite the method reporting that the signature is valid. This can happen because the entity doing the tampering just has to generate a new key and re-sign the tampered document with that new key. So, unless your application verifies that the public key is an expected value, the document should be treated as if it were tampered with. This requires that your application examine the public key embedded within the document and verify it against a list of known values for the document context. For example, if the document could be understood to be issued by a known user, you'd check the key against a list of known keys used by that user. -You can also verify the key after processing the document by using the method, instead of using the method. But, for the optimal security, you should verify the key beforehand. +You can also verify the key after processing the document by using the method, instead of using the method. But, for the optimal security, you should verify the key beforehand. Alternately, consider trying the user's registered public keys, rather than reading what's in the `` element. @@ -121,7 +121,7 @@ Alternately, consider trying the user's registered public keys, rather than read The optional `` element is a child of the `` element and contains one or more X509 certificates or identifiers for X509 certificates. The data in the `` element should also not be inherently trusted. -When verifying a document with the embedded `` element, .NET verifies only that the data resolves to an X509 certificate whose public key can be successfully used to validate the document signature. Unlike calling the method with the `verifySignatureOnly` parameter set to `false`, no revocation check is performed, no chain trust is checked, and no expiration is verified. Even if your application extracts the certificate itself and passes it to the method with the `verifySignatureOnly` parameter set to `false`, that is still not sufficient validation to prevent document tampering. The certificate still needs to be verified as being appropriate for the document being signed. +When verifying a document with the embedded `` element, .NET verifies only that the data resolves to an X509 certificate whose public key can be successfully used to validate the document signature. Unlike calling the method with the `verifySignatureOnly` parameter set to `false`, no revocation check is performed, no chain trust is checked, and no expiration is verified. Even if your application extracts the certificate itself and passes it to the method with the `verifySignatureOnly` parameter set to `false`, that is still not sufficient validation to prevent document tampering. The certificate still needs to be verified as being appropriate for the document being signed. Using an embedded signing certificate can provide useful key rotation strategies, whether in the `` section or in the document content. When using this approach an application should extract the certificate manually and perform validation similar to: @@ -139,7 +139,7 @@ Using an embedded signing certificate can provide useful key rotation strategies If you are interoperating with a specification which has dictated specific values (such as XrML), then you need to follow the specification. If you have an enveloped signature (such as when signing the whole document), then you need to use (represented by the class). You can specify the implicit XML-C14N transform as well, but it's not necessary. For an enveloping or detached signature, no transforms are required. The implicit XML-C14N transform takes care of everything. -With the security updated introduced by the [Microsoft Security Bulletin MS16-035](/security-updates/securitybulletins/2016/ms16-035), .NET has restricted what transforms can be used in document verification by default, with untrusted transforms causing to always return `false`. In particular, transforms which require additional input (specified as child elements in the XML) are no longer allowed due to their susceptibility of abuse by malicious users. The W3C advises avoiding the XPath and XSLT transforms, which are the two main transforms affected by these restrictions. +With the security updated introduced by the [Microsoft Security Bulletin MS16-035](/security-updates/securitybulletins/2016/ms16-035), .NET has restricted what transforms can be used in document verification by default, with untrusted transforms causing to always return `false`. In particular, transforms which require additional input (specified as child elements in the XML) are no longer allowed due to their susceptibility of abuse by malicious users. The W3C advises avoiding the XPath and XSLT transforms, which are the two main transforms affected by these restrictions. ## The problem with external references diff --git a/docs/fundamentals/runtime-libraries/system-security-securestring.md b/docs/fundamentals/runtime-libraries/system-security-securestring.md index a19eaa859eac1..274e517858158 100644 --- a/docs/fundamentals/runtime-libraries/system-security-securestring.md +++ b/docs/fundamentals/runtime-libraries/system-security-securestring.md @@ -10,12 +10,12 @@ ms.date: 12/31/2023 [!INCLUDE [context](includes/context.md)] - is a string type that provides a measure of security. It tries to avoid storing potentially sensitive strings in process memory as plain text. (For limitations, however, see the [How secure is SecureString?](#how-secure-is-securestring) section.) The value of an instance of is automatically protected using a mechanism supported by the underlying platform when the instance is initialized or when the value is modified. Your application can render the instance immutable and prevent further modification by invoking the method. + is a string type that provides a measure of security. It tries to avoid storing potentially sensitive strings in process memory as plain text. (For limitations, however, see the [How secure is SecureString?](#how-secure-is-securestring) section.) The value of an instance of is automatically protected using a mechanism supported by the underlying platform when the instance is initialized or when the value is modified. Your application can render the instance immutable and prevent further modification by invoking the method. The maximum length of a instance is 65,536 characters. > [!IMPORTANT] -> This type implements the interface. When you have finished using an instance of the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. +> This type implements the interface. When you have finished using an instance of the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. The class and its members are not visible to COM. For more information, see . @@ -23,7 +23,7 @@ The class and its members are not visible to An instance of the class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created, and it is not possible to predict when the instance will be deleted from computer memory. Because instances are immutable, operations that appear to modify an existing instance actually create a copy of it to manipulate. Consequently, if a object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory. -A object is similar to a object in that it has a text value. However, the value of a object is pinned in memory, may use a protection mechanism, such as encryption, provided by the underlying operating system, can be modified until your application marks it as read-only, and can be deleted from computer memory either by your application calling the method or by the .NET garbage collector. +A object is similar to a object in that it has a text value. However, the value of a object is pinned in memory, may use a protection mechanism, such as encryption, provided by the underlying operating system, can be modified until your application marks it as read-only, and can be deleted from computer memory either by your application calling the method or by the .NET garbage collector. For a discussion of the limitations of the class, see the [How secure is SecureString?](#how-secure-is-securestring) section. @@ -35,32 +35,32 @@ Instantiate a object You instantiate a object by calling its parameterless constructor. Add characters to a object -You can add a single character at a time to a object by calling its or method. +You can add a single character at a time to a object by calling its or method. > [!IMPORTANT] -> A object should never be constructed from a , because the sensitive data is already subject to the memory persistence consequences of the immutable class. The best way to construct a object is from a character-at-a-time unmanaged source, such as the method. +> A object should never be constructed from a , because the sensitive data is already subject to the memory persistence consequences of the immutable class. The best way to construct a object is from a character-at-a-time unmanaged source, such as the method. Remove characters from a object -You can replace an individual character by calling the method, remove an individual character by calling the method, or remove all characters from the instance by calling the method. +You can replace an individual character by calling the method, remove an individual character by calling the method, or remove all characters from the instance by calling the method. Make the object read-only -Once you have defined the string that the object represents, you call its method to make the string read-only. +Once you have defined the string that the object represents, you call its method to make the string read-only. Get information about the object -The class has only two members that provide information about the string: its property, which indicates the number of UTF16-encoded code units in the string; and the , method, which indicates whether the instance is read-only. +The class has only two members that provide information about the string: its property, which indicates the number of UTF16-encoded code units in the string; and the , method, which indicates whether the instance is read-only. Release the memory allocated to the instance -Because implements the interface, you release its memory by calling the method. +Because implements the interface, you release its memory by calling the method. -The class has no members that inspect, compare, or convert the value of a . The absence of such members helps protect the value of the instance from accidental or malicious exposure. Use appropriate members of the class, such as the method, to manipulate the value of a object. +The class has no members that inspect, compare, or convert the value of a . The absence of such members helps protect the value of the instance from accidental or malicious exposure. Use appropriate members of the class, such as the method, to manipulate the value of a object. The .NET Class Library commonly uses instances in the following ways: -- To provide password information to a process by using the structure or by calling an overload of the method that has a parameter of type . +- To provide password information to a process by using the structure or by calling an overload of the method that has a parameter of type . - To provide network password information by calling a class constructor that has a parameter of type or by using the property. -- To provide password information for SQL Server Authentication by calling the constructor or retrieving the value of the property. +- To provide password information for SQL Server Authentication by calling the constructor or retrieving the value of the property. - To pass a string to unmanaged code. For more information, see the [SecureString and interop](#securestring-and-interop) section. @@ -68,25 +68,25 @@ The .NET Class Library commonly uses instanc Because the operating system does not directly support , you must convert the value of the object to the required string type before passing the string to a native method. The class has five methods that do this: -- , which converts the string value to a binary string (BSTR) recognized by COM. +- , which converts the string value to a binary string (BSTR) recognized by COM. -- and , which copy the string value to an ANSI string in unmanaged memory. +- and , which copy the string value to an ANSI string in unmanaged memory. -- and , which copy the string value to a Unicode string in unmanaged memory. +- and , which copy the string value to a Unicode string in unmanaged memory. Each of these methods creates a clear-text string in unmanaged memory. It is the responsibility of the developer to zero out and free that memory as soon as it is no longer needed. Each of the string conversion and memory allocation methods has a corresponding method to zero out and free the allocated memory: |Allocation and conversion method|Zero and free method| |--------------------------------------|--------------------------| -||| -||| -||| -||| -||| +||| +||| +||| +||| +||| ## How secure is SecureString? -When created properly, a instance provides more data protection than a . When creating a string from a character-at-a-time source, creates multiple intermediate in memory, whereas creates just a single instance. Garbage collection of objects is non-deterministic. In addition, because its memory is not pinned, the garbage collector will make additional copies of values when moving and compacting memory. In contrast, the memory allocated to a object is pinned, and that memory can be freed by calling the method. +When created properly, a instance provides more data protection than a . When creating a string from a character-at-a-time source, creates multiple intermediate in memory, whereas creates just a single instance. Garbage collection of objects is non-deterministic. In addition, because its memory is not pinned, the garbage collector will make additional copies of values when moving and compacting memory. In contrast, the memory allocated to a object is pinned, and that memory can be freed by calling the method. Although data stored in a instance is more secure than data stored in a instance, there are significant limitations on how secure a instance is. These include: @@ -100,7 +100,7 @@ Even if the implementation is able to take a - Because Windows doesn't offer a secure string implementation at the operating system level, .NET still has to convert the secure string value to its plain text representation in order to use it. -- Whenever the value of the secure string is modified by methods such as or , it must be decrypted (that is, converted back to plain text), modified, and then encrypted again. +- Whenever the value of the secure string is modified by methods such as or , it must be decrypted (that is, converted back to plain text), modified, and then encrypted again. - If the secure string is used in an interop call, it must be converted to an ANSI string, a Unicode string, or a binary string (BSTR). For more information, see the [SecureString and interop](#securestring-and-interop) section. diff --git a/docs/fundamentals/runtime-libraries/system-single-compareto.md b/docs/fundamentals/runtime-libraries/system-single-compareto.md index fbfca2e983cb5..77afb3c1e2c23 100644 --- a/docs/fundamentals/runtime-libraries/system-single-compareto.md +++ b/docs/fundamentals/runtime-libraries/system-single-compareto.md @@ -11,9 +11,9 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -Values must be identical to be considered equal. Particularly when floating-point values depend on multiple mathematical operations, it's common for them to lose precision and for their values to be nearly identical except for their least significant digits. Because of this, the return value of the method may seem surprising at times. For example, multiplication by a particular value followed by division by the same value should produce the original value, but in the following example, the computed value turns out to be greater than the original value. Showing all significant digits of the two values by using the "R" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) indicates that the computed value differs from the original value in its least significant digits. For information about handling such comparisons, see the Remarks section of the method. +Values must be identical to be considered equal. Particularly when floating-point values depend on multiple mathematical operations, it's common for them to lose precision and for their values to be nearly identical except for their least significant digits. Because of this, the return value of the method may seem surprising at times. For example, multiplication by a particular value followed by division by the same value should produce the original value, but in the following example, the computed value turns out to be greater than the original value. Showing all significant digits of the two values by using the "R" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) indicates that the computed value differs from the original value in its least significant digits. For information about handling such comparisons, see the Remarks section of the method. -Although an object whose value is is not considered equal to another object whose value is (even itself), the interface requires that `A.CompareTo(A)` return zero. +Although an object whose value is is not considered equal to another object whose value is (even itself), the interface requires that `A.CompareTo(A)` return zero. ## CompareTo(System.Object) @@ -27,7 +27,7 @@ This method is implemented to support the interface. ## CompareTo(System.Single) -This method implements the interface and performs slightly better than the overload because it doesn't have to convert the `value` parameter to an object. +This method implements the interface and performs slightly better than the overload because it doesn't have to convert the `value` parameter to an object. :::code language="csharp" source="./snippets/System/Single/CompareTo/csharp/compareto2.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Single/CompareTo/fsharp/compareto2.fs" id="Snippet1"::: @@ -35,7 +35,7 @@ This method implements the method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. +Depending on your programming language, it might be possible to code a method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. For example, suppose the instance type is and the parameter type is . The Microsoft C# compiler generates instructions to represent the value of the parameter as a object, then generates a method that compares the values of the instance and the widened representation of the parameter. diff --git a/docs/fundamentals/runtime-libraries/system-single-equals.md b/docs/fundamentals/runtime-libraries/system-single-equals.md index 6bd29755f84a6..81b554ed638fc 100644 --- a/docs/fundamentals/runtime-libraries/system-single-equals.md +++ b/docs/fundamentals/runtime-libraries/system-single-equals.md @@ -11,11 +11,11 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The method implements the interface, and performs slightly better than because it does not have to convert the `obj` parameter to an object. +The method implements the interface, and performs slightly better than because it does not have to convert the `obj` parameter to an object. ## Widening conversions -Depending on your programming language, it might be possible to code an method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. +Depending on your programming language, it might be possible to code an method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. For example, suppose the instance type is and the parameter type is . The Microsoft C# compiler generates instructions to represent the value of the parameter as a object, and then generates a method that compares the values of the instance and the widened representation of the parameter. @@ -23,7 +23,7 @@ Consult your programming language's documentation to determine if its compiler p ## Precision in comparisons -The method should be used with caution, because two apparently equivalent values can be unequal because of the differing precision of the two values. The following example reports that the value .3333 and the returned by dividing 1 by 3 are unequal. +The method should be used with caution, because two apparently equivalent values can be unequal because of the differing precision of the two values. The following example reports that the value .3333 and the returned by dividing 1 by 3 are unequal. :::code language="csharp" source="./snippets/System/Single/Epsilon/csharp/SingleEquals_25051.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Single/Epsilon/fsharp/SingleEquals_25051.fs" id="Snippet1"::: @@ -40,7 +40,7 @@ In this case, the values are equal. > [!NOTE] > Because defines the minimum expression of a positive value whose range is near zero, the margin of difference must be greater than . Typically, it is many times greater than . Because of this, we recommend that you do not use when comparing values for equality. -A second technique that avoids the problems associated with comparing for equality involves comparing the difference between two floating-point numbers with some absolute value. If the difference is less than or equal to that absolute value, the numbers are equal. If it is greater, the numbers are not equal. One way to do this is to arbitrarily select an absolute value. However, this is problematic, because an acceptable margin of difference depends on the magnitude of the values. A second way takes advantage of a design feature of the floating-point format: The difference between the mantissa components in the integer representations of two floating-point values indicates the number of possible floating-point values that separates the two values. For example, the difference between 0.0 and is 1, because is the smallest representable value when working with a whose value is zero. The following example uses this technique to compare .33333 and 1/3, which are the two values that the previous code example with the method found to be unequal. Note that the example uses the and methods to convert a single-precision floating-point value to its integer representation. +A second technique that avoids the problems associated with comparing for equality involves comparing the difference between two floating-point numbers with some absolute value. If the difference is less than or equal to that absolute value, the numbers are equal. If it is greater, the numbers are not equal. One way to do this is to arbitrarily select an absolute value. However, this is problematic, because an acceptable margin of difference depends on the magnitude of the values. A second way takes advantage of a design feature of the floating-point format: The difference between the mantissa components in the integer representations of two floating-point values indicates the number of possible floating-point values that separates the two values. For example, the difference between 0.0 and is 1, because is the smallest representable value when working with a whose value is zero. The following example uses this technique to compare .33333 and 1/3, which are the two values that the previous code example with the method found to be unequal. Note that the example uses the and methods to convert a single-precision floating-point value to its integer representation. :::code language="csharp" source="./snippets/System/Single/Equals/csharp/equalsabs1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Single/Equals/fsharp/equalsabs1.fs" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-single.md b/docs/fundamentals/runtime-libraries/system-single.md index dfda8ed0f1311..e3aac6130214b 100644 --- a/docs/fundamentals/runtime-libraries/system-single.md +++ b/docs/fundamentals/runtime-libraries/system-single.md @@ -69,11 +69,11 @@ The limited precision of a floating-point number has several consequences: :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/precisionlist1.fs" id="Snippet5"::: :::code language="vb" source="./snippets/System/Double/Overview/vb/precisionlist1.vb" id="Snippet5"::: - To avoid this problem, either use the data type in place of the data type, or use the method so that both values have the same precision. + To avoid this problem, either use the data type in place of the data type, or use the method so that both values have the same precision. ## Test for equality -To be considered equal, two values must represent identical values. However, because of differences in precision between values, or because of a loss of precision by one or both values, floating-point values that are expected to be identical often turn out to be unequal due to differences in their least significant digits. As a result, calls to the method to determine whether two values are equal, or calls to the method to determine the relationship between two values, often yield unexpected results. This is evident in the following example, where two apparently equal values turn out to be unequal, because the first value has 7 digits of precision, whereas the second value has 9. +To be considered equal, two values must represent identical values. However, because of differences in precision between values, or because of a loss of precision by one or both values, floating-point values that are expected to be identical often turn out to be unequal due to differences in their least significant digits. As a result, calls to the method to determine whether two values are equal, or calls to the method to determine the relationship between two values, often yield unexpected results. This is evident in the following example, where two apparently equal values turn out to be unequal, because the first value has 7 digits of precision, whereas the second value has 9. :::code language="csharp" source="./snippets/System/Single/Overview/csharp/comparison1.cs" id="Snippet9"::: :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/comparison1.fs" id="Snippet9"::: @@ -85,9 +85,9 @@ Calculated values that follow different code paths and that are manipulated in d :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/comparison2.fs" id="Snippet10"::: :::code language="vb" source="./snippets/System/Single/Overview/vb/comparison2.vb" id="Snippet10"::: -In cases where a loss of precision is likely to affect the result of a comparison, you can use the following techniques instead of calling the or method: +In cases where a loss of precision is likely to affect the result of a comparison, you can use the following techniques instead of calling the or method: -- Call the method to ensure that both values have the same precision. The following example modifies a previous example to use this approach so that two fractional values are equivalent. +- Call the method to ensure that both values have the same precision. The following example modifies a previous example to use this approach so that two fractional values are equivalent. :::code language="csharp" source="./snippets/System/Single/Overview/csharp/comparison3.cs" id="Snippet11"::: :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/comparison3.fs" id="Snippet11"::: @@ -184,26 +184,26 @@ For more information on the conversion of numeric types, see [Type Conversion in The structure and related types provide methods to perform the following categories of operations: -- **Comparison of values**. You can call the method to determine whether two values are equal, or the method to determine the relationship between two values. +- **Comparison of values**. You can call the method to determine whether two values are equal, or the method to determine the relationship between two values. The structure also supports a complete set of comparison operators. For example, you can test for equality or inequality, or determine whether one value is greater than or equal to another value. If one of the operands is a , the value is converted to a before performing the comparison. If one of the operands is an integral type, it is converted to a before performing the comparison. Although these are widening conversions, they may involve a loss of precision. > [!WARNING] > Because of differences in precision, two values that you expect to be equal may turn out to be unequal, which affects the result of the comparison. See the [Test for equality](#test-for-equality) section for more information about comparing two values. - You can also call the , , , and methods to test for these special values. + You can also call the , , , and methods to test for these special values. - **Mathematical operations**. Common arithmetic operations such as addition, subtraction, multiplication, and division are implemented by language compilers and Common Intermediate Language (CIL) instructions rather than by methods. If the other operand in a mathematical operation is a , the is converted to a before performing the operation, and the result of the operation is also a value. If the other operand is an integral type, it is converted to a before performing the operation, and the result of the operation is also a value. - You can perform other mathematical operations by calling `static` (`Shared` in Visual Basic) methods in the class. These include additional methods commonly used for arithmetic (such as , , and ), geometry (such as and ), and calculus (such as ). In all cases, the value is converted to a . + You can perform other mathematical operations by calling `static` (`Shared` in Visual Basic) methods in the class. These include additional methods commonly used for arithmetic (such as , , and ), geometry (such as and ), and calculus (such as ). In all cases, the value is converted to a . - You can also manipulate the individual bits in a value. The method returns its bit pattern in a byte array. By passing that byte array to the method, you can also preserve the value's bit pattern in a 32-bit integer. + You can also manipulate the individual bits in a value. The method returns its bit pattern in a byte array. By passing that byte array to the method, you can also preserve the value's bit pattern in a 32-bit integer. -- **Rounding**. Rounding is often used as a technique for reducing the impact of differences between values caused by problems of floating-point representation and precision. You can round a value by calling the method. However, note that the value is converted to a before the method is called, and the conversion can involve a loss of precision. +- **Rounding**. Rounding is often used as a technique for reducing the impact of differences between values caused by problems of floating-point representation and precision. You can round a value by calling the method. However, note that the value is converted to a before the method is called, and the conversion can involve a loss of precision. -- **Formatting**. You can convert a value to its string representation by calling the method or by using the [composite formatting](../../standard/base-types/composite-formatting.md) feature. For information about how format strings control the string representation of floating-point values, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md). +- **Formatting**. You can convert a value to its string representation by calling the method or by using the [composite formatting](../../standard/base-types/composite-formatting.md) feature. For information about how format strings control the string representation of floating-point values, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md). -- **Parsing strings**. You can convert the string representation of a floating-point value to a value by calling the or method. If the parse operation fails, the method throws an exception, whereas the method returns `false`. +- **Parsing strings**. You can convert the string representation of a floating-point value to a value by calling the or method. If the parse operation fails, the method throws an exception, whereas the method returns `false`. - **Type conversion**. The structure provides an explicit interface implementation for the interface, which supports conversion between any two standard .NET data types. Language compilers also support the implicit conversion of values for all other standard numeric types except for the conversion of to values. Conversion of a value of any standard numeric type other than a to a is a widening conversion and does not require the use of a casting operator or conversion method. diff --git a/docs/fundamentals/runtime-libraries/system-span{t}.md b/docs/fundamentals/runtime-libraries/system-span{t}.md index 64ae36d1b056b..83204b6b17b3e 100644 --- a/docs/fundamentals/runtime-libraries/system-span{t}.md +++ b/docs/fundamentals/runtime-libraries/system-span{t}.md @@ -10,12 +10,12 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The type is a [ref struct](../../csharp/language-reference/builtin-types/ref-struct.md) that is allocated on the stack rather than on the managed heap. Ref struct types have a number of restrictions to ensure that they cannot be promoted to the managed heap, including that they can't be boxed, they can't be assigned to variables of type , `dynamic` or to any interface type, they can't be fields in a reference type, and they can't be used across `await` and `yield` boundaries. In addition, calls to two methods, and , throw a . +The type is a [ref struct](../../csharp/language-reference/builtin-types/ref-struct.md) that is allocated on the stack rather than on the managed heap. Ref struct types have a number of restrictions to ensure that they cannot be promoted to the managed heap, including that they can't be boxed, they can't be assigned to variables of type , `dynamic` or to any interface type, they can't be fields in a reference type, and they can't be used across `await` and `yield` boundaries. In addition, calls to two methods, and , throw a . > [!IMPORTANT] -> Because it is a stack-only type, `Span` is unsuitable for many scenarios that require storing references to buffers on the heap. This is true, for example, of routines that make asynchronous method calls. For such scenarios, you can use the complementary and types. +> Because it is a stack-only type, `Span` is unsuitable for many scenarios that require storing references to buffers on the heap. This is true, for example, of routines that make asynchronous method calls. For such scenarios, you can use the complementary and types. -For spans that represent immutable or read-only structures, use . +For spans that represent immutable or read-only structures, use . ## Memory @@ -50,12 +50,12 @@ The following example creates a slice of the middle five elements of a 10-elemen ## Slices -`Span` includes two overloads of the method that form a slice out of the current span that starts at a specified index. This makes it possible to treat the data in a `Span` as a set of logical chunks that can be processed as needed by portions of a data processing pipeline with minimal performance impact. For example, since modern server protocols are often text-based, manipulation of strings and substrings is particularly important. In the class, the major method for extracting substrings is . For data pipelines that rely on extensive string manipulation, its use offers some performance penalties, since it: +`Span` includes two overloads of the method that form a slice out of the current span that starts at a specified index. This makes it possible to treat the data in a `Span` as a set of logical chunks that can be processed as needed by portions of a data processing pipeline with minimal performance impact. For example, since modern server protocols are often text-based, manipulation of strings and substrings is particularly important. In the class, the major method for extracting substrings is . For data pipelines that rely on extensive string manipulation, its use offers some performance penalties, since it: 1. Creates a new string to hold the substring. 2. Copies a subset of the characters from the original string to the new string. -This allocation and copy operation can be eliminated by using either `Span` or , as the following example shows: +This allocation and copy operation can be eliminated by using either `Span` or , as the following example shows: :::code language="csharp" source="./snippets/System/Span/Slice/csharp/Program2.cs"::: :::code language="fsharp" source="./snippets/System/Span/Slice/fsharp/Program2.fs"::: diff --git a/docs/fundamentals/runtime-libraries/system-string-ctor.md b/docs/fundamentals/runtime-libraries/system-string-ctor.md index b6d7f4eae73fb..24fea37fde822 100644 --- a/docs/fundamentals/runtime-libraries/system-string-ctor.md +++ b/docs/fundamentals/runtime-libraries/system-string-ctor.md @@ -36,12 +36,12 @@ Permission: , requires full trus Permission: , requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code. `String(SByte* value)`\ -**(Not CLS-compliant)** Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers. The array is assumed to represent a string encoded using the current system code page (that is, the encoding specified by ). The constructor processes characters from `value` starting from the location specified by the pointer until a null character (0x00) is reached ([Example 6: Instantiate a string from a pointer to a signed byte array](#example-6-instantiate-a-string-from-a-pointer-to-a-signed-byte-array)). +**(Not CLS-compliant)** Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers. The array is assumed to represent a string encoded using the current system code page (that is, the encoding specified by ). The constructor processes characters from `value` starting from the location specified by the pointer until a null character (0x00) is reached ([Example 6: Instantiate a string from a pointer to a signed byte array](#example-6-instantiate-a-string-from-a-pointer-to-a-signed-byte-array)). Permission: , requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code. `String(SByte* value, Int32 startIndex, Int32 length)`\ -**(Not CLS-compliant)** Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers, a starting position within that array, and a length. The array is assumed to represent a string encoded using the current system code page (that is, the encoding specified by ). The constructor processes characters from value starting at `startIndex` and ending at `startIndex` + `length` - 1 ([Example 6: Instantiate a string from a pointer to a signed byte array](#example-6-instantiate-a-string-from-a-pointer-to-a-signed-byte-array)). +**(Not CLS-compliant)** Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers, a starting position within that array, and a length. The array is assumed to represent a string encoded using the current system code page (that is, the encoding specified by ). The constructor processes characters from value starting at `startIndex` and ending at `startIndex` + `length` - 1 ([Example 6: Instantiate a string from a pointer to a signed byte array](#example-6-instantiate-a-string-from-a-pointer-to-a-signed-byte-array)). Permission: , requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code. @@ -59,7 +59,7 @@ Here is a complete list of parameters used by constructors | `value` | [] | An array of Unicode characters. | | `c` | | A Unicode character. | | `startIndex` | |The starting position in `value` of the first character in the new string.

Default value: 0| -| `length` | |The number of characters in `value` to include in the new string.

Default value: | +| `length` | |The number of characters in `value` to include in the new string.

Default value: | | `count` | |The number of times the character `c` is repeated in the new string. If `count` is zero, the value of the new object is .| Here is a complete list of parameters used by constructors that include a pointer parameter. For the parameters used by each overload, see the overload syntax above. @@ -68,8 +68,8 @@ Here is a complete list of parameters used by constructors |-----------|------|-------------| |`value`|*

-or-

\*|A pointer to a null-terminated array of Unicode characters or an array of 8-bit signed integers. If `value` is `null` or an empty array, the value of the new string is .| |`startIndex`||The index of the array element that defines the first character in the new string.

Default value: 0| -|`length`||The number of array elements to use to create the new string. If length is zero, the constructor creates a string whose value is .

Default value: | -|`enc`||An object that specifies how the `value` array is encoded.

Default value: , or the system's current ANSI code page| +|`length`||The number of array elements to use to create the new string. If length is zero, the constructor creates a string whose value is .

Default value: | +|`enc`||An object that specifies how the `value` array is encoded.

Default value: , or the system's current ANSI code page| ## Exceptions @@ -85,9 +85,9 @@ Here's a list of exceptions thrown by constructors that include pointer paramete | Exception | Condition | Thrown by | |-----------|-----------|-----------| ||`value` specifies an array that contains an invalid Unicode character.

-or-

`value` or `value` + `startIndex` specifies an address that is less than 64K.

-or-

A new instance could not be initialized from the `value` byte array because `value` does not use the default code page encoding.|All constructors with pointers.| -||`value` is null.|



| +||`value` is null.|



| ||The current process does not have read access to all the addressed characters.

-or-

`startIndex` or `length` is less than zero, `value` + `startIndex` cause a pointer overflow, or the current process does not have read access to all the addressed characters.

-or-

The length of the new string is too large to allocate.|All constructors with pointers.| -||`value`, or `value` + `startIndex` + `length` - 1, specifies an invalid address.|



| +||`value`, or `value` + `startIndex` + `length` - 1, specifies an invalid address.|



| ## Which method do I call? @@ -97,10 +97,10 @@ Here's a list of exceptions thrown by constructors that include pointer paramete |Create a string from an entire character array.| ([Example 2: Use a character array](#example-2-use-a-character-array))| |Create a string from a portion of a character array.| ([Example 3: Use a portion of a character array and repeating a single character](#example-3-use-a-portion-of-a-character-array-and-repeating-a-single-character))| |Create a string that repeats the same character multiple times.| ([Example 3: Use a portion of a character array and repeating a single character](#example-3-use-a-portion-of-a-character-array-and-repeating-a-single-character))| -|Create a string from a pointer to a Unicode or wide character array.|| -|Create a string from a portion of a Unicode or wide character array by using its pointer.|| -|Create a string from a C++ `char` array.|,

-or-

| -|Create a string from ASCII characters.|| +|Create a string from a pointer to a Unicode or wide character array.|| +|Create a string from a portion of a Unicode or wide character array by using its pointer.|| +|Create a string from a C++ `char` array.|,

-or-

| +|Create a string from ASCII characters.|| ## Create strings @@ -112,16 +112,16 @@ The most commonly used technique for creating strings programmatically is simple - From a single character that is duplicated zero, one, or more times, by using the constructor. If `count` is zero, the value of the new string is . -- From a pointer to a null-terminated character array, by using the or constructor. Either the entire array or a specified range can be used to initialize the string. The constructor copies a sequence of Unicode characters starting from the specified pointer or from the specified pointer plus `startIndex` and continuing to the end of the array or for `length` characters. If `value` is a null pointer or `length` is zero, the constructor creates a string whose value is . If the copy operation proceeds to the end of the array and the array is not null-terminated, the constructor behavior is system-dependent. Such a condition might cause an access violation. +- From a pointer to a null-terminated character array, by using the or constructor. Either the entire array or a specified range can be used to initialize the string. The constructor copies a sequence of Unicode characters starting from the specified pointer or from the specified pointer plus `startIndex` and continuing to the end of the array or for `length` characters. If `value` is a null pointer or `length` is zero, the constructor creates a string whose value is . If the copy operation proceeds to the end of the array and the array is not null-terminated, the constructor behavior is system-dependent. Such a condition might cause an access violation. - If the array contains any embedded null characters (U+0000 or '\0') and the overload is called, the string instance contains `length` characters including any embedded nulls. The following example shows what happens when a pointer to an array of 10 elements that includes two null characters is passed to the method. Because the address is the beginning of the array and all elements in the array are to be added to the string, the constructor instantiates a string with ten characters, including two embedded nulls. On the other hand, if the same array is passed to the constructor, the result is a four-character string that does not include the first null character. + If the array contains any embedded null characters (U+0000 or '\0') and the overload is called, the string instance contains `length` characters including any embedded nulls. The following example shows what happens when a pointer to an array of 10 elements that includes two null characters is passed to the method. Because the address is the beginning of the array and all elements in the array are to be added to the string, the constructor instantiates a string with ten characters, including two embedded nulls. On the other hand, if the same array is passed to the constructor, the result is a four-character string that does not include the first null character. :::code language="csharp" source="./snippets/System/String/.ctor/csharp/chptrctor_null.cs" id="Snippet5"::: :::code language="fsharp" source="./snippets/System/String/.ctor/fsharp/chptrctor_null.fs" id="Snippet5"::: The array must contain Unicode characters. In C++, this means that the character array must be defined either as the managed [] type or the unmanaged`wchar_t`[] type. - If the overload is called and the array is not null-terminated, or if the overload is called and `startIndex` + `length`-1 includes a range that is outside the memory allocated for the sequence of characters, the behavior of the constructor is system-dependent, and an access violation may occur. + If the overload is called and the array is not null-terminated, or if the overload is called and `startIndex` + `length`-1 includes a range that is outside the memory allocated for the sequence of characters, the behavior of the constructor is system-dependent, and an access violation may occur. - From a pointer to a signed byte array. Either the entire array or a specified range can be used to initialize the string. The sequence of bytes can be interpreted by using the default code page encoding, or an encoding can be specified in the constructor call. If the constructor tries to instantiate a string from an entire array that is not null-terminated, or if the range of the array from `value` + `startIndex` to `value` + `startIndex` + `length` -1 is outside of the memory allocated for the array, the behavior of this constructor is system-dependent, and an access violation may occur. @@ -129,12 +129,12 @@ The most commonly used technique for creating strings programmatically is simple :::code language="cpp" source="./snippets/System/String/.ctor/cpp/sbyte_ctor1.cpp" id="Snippet4"::: - If the array contains any null characters ('\0') or bytes whose value is 0 and the overload is called, the string instance contains `length` characters including any embedded nulls. The following example shows what happens when a pointer to an array of 10 elements that includes two null characters is passed to the method. Because the address is the beginning of the array and all elements in the array are to be added to the string, the constructor instantiates a string with ten characters, including two embedded nulls. On the other hand, if the same array is passed to the constructor, the result is a four-character string that does not include the first null character. + If the array contains any null characters ('\0') or bytes whose value is 0 and the overload is called, the string instance contains `length` characters including any embedded nulls. The following example shows what happens when a pointer to an array of 10 elements that includes two null characters is passed to the method. Because the address is the beginning of the array and all elements in the array are to be added to the string, the constructor instantiates a string with ten characters, including two embedded nulls. On the other hand, if the same array is passed to the constructor, the result is a four-character string that does not include the first null character. :::code language="csharp" source="./snippets/System/String/.ctor/csharp/ptrctor_null.cs" id="Snippet6"::: :::code language="fsharp" source="./snippets/System/String/.ctor/fsharp/ptrctor_null.fs" id="Snippet6"::: - Because the and constructors interpret `value` by using the default ANSI code page, calling these constructors with identical byte arrays may create strings that have different values on different systems. + Because the and constructors interpret `value` by using the default ANSI code page, calling these constructors with identical byte arrays may create strings that have different values on different systems. ## Handle repetitive strings @@ -184,7 +184,7 @@ The following example examines the elements of a character array for either a pe ## Example 6: Instantiate a string from a pointer to a signed byte array -The following example demonstrates how you can create an instance of the class with the constructor. +The following example demonstrates how you can create an instance of the class with the constructor. :::code language="csharp" source="./snippets/System/String/.ctor/csharp/source.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/String/.ctor/fsharp/source.fs" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-string-format.md b/docs/fundamentals/runtime-libraries/system-string-format.md index e749eec39f702..f57727180150d 100644 --- a/docs/fundamentals/runtime-libraries/system-string-format.md +++ b/docs/fundamentals/runtime-libraries/system-string-format.md @@ -15,7 +15,7 @@ dev_langs: ## Examples -Numerous examples that call the method are interspersed throughout this article. You can also download a complete set of `String.Format` examples, which are included a [.NET Core project for C#](/samples/dotnet/samples/string-format/). +Numerous examples that call the method are interspersed throughout this article. You can also download a complete set of `String.Format` examples, which are included a [.NET Core project for C#](/samples/dotnet/samples/string-format/). The following are some of the examples included in the article: @@ -45,7 +45,7 @@ The following are some of the examples included in the article: ## Get started with the String.Format method -Use if you need to insert the value of an object, variable, or expression into another string. For example, you can insert the value of a value into a string to display it to the user as a single string: +Use if you need to insert the value of an object, variable, or expression into another string. For example, you can insert the value of a value into a string to display it to the user as a single string: :::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/starting2.cs" id="Snippet35"::: :::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/starting2.fs" id="Snippet35"::: @@ -61,7 +61,7 @@ Besides formatting, you can also control alignment and spacing. ### Insert a string - starts with a format string, followed by one or more objects or expressions that will be converted to strings and inserted at a specified place in the format string. For example: + starts with a format string, followed by one or more objects or expressions that will be converted to strings and inserted at a specified place in the format string. For example: :::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/starting1.cs" id="Snippet30"::: :::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/starting1.fs" id="Snippet30"::: @@ -107,19 +107,19 @@ The following example is similar to the previous one, except that it left-aligns :::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/starting1.fs" id="Snippet34"::: :::code language="vb" source="./snippets/System/String/Format/vb/starting1.vb" id="Snippet34"::: - makes use of the composite formatting feature. For more information, see [Composite Formatting](../../standard/base-types/composite-formatting.md). + makes use of the composite formatting feature. For more information, see [Composite Formatting](../../standard/base-types/composite-formatting.md). ## Which method do I call? | Objective | Method to call | |-----------|----------------| -|Format one or more objects by using the conventions of the current culture.|Except for the overloads that include a `provider` parameter, the remaining overloads include a parameter followed by one or more object parameters. Because of this, you don't have to determine which overload you intend to call. Your language compiler selects the appropriate overload from among the overloads that don't have a `provider` parameter, based on your argument list. For example, if your argument list has five arguments, the compiler calls the method.| -|Format one or more objects by using the conventions of a specific culture.|Each overload that begins with a `provider` parameter is followed by a parameter and one or more object parameters. Because of this, you don't have to determine which specific overload you intend to call. Your language compiler selects the appropriate overload from among the overloads that have a `provider` parameter, based on your argument list. For example, if your argument list has five arguments, the compiler calls the method.| +|Format one or more objects by using the conventions of the current culture.|Except for the overloads that include a `provider` parameter, the remaining overloads include a parameter followed by one or more object parameters. Because of this, you don't have to determine which overload you intend to call. Your language compiler selects the appropriate overload from among the overloads that don't have a `provider` parameter, based on your argument list. For example, if your argument list has five arguments, the compiler calls the method.| +|Format one or more objects by using the conventions of a specific culture.|Each overload that begins with a `provider` parameter is followed by a parameter and one or more object parameters. Because of this, you don't have to determine which specific overload you intend to call. Your language compiler selects the appropriate overload from among the overloads that have a `provider` parameter, based on your argument list. For example, if your argument list has five arguments, the compiler calls the method.| |Perform a custom formatting operation either with an implementation or an implementation.|Any of the four overloads with a `provider` parameter. The compiler selects the appropriate overload from among the overloads that have a `provider` parameter, based on your argument list.| ## The Format method in brief -Each overload of the method uses the [composite formatting feature](../../standard/base-types/composite-formatting.md) to include zero-based indexed placeholders, called *format items*, in a composite format string. At runtime, each format item is replaced with the string representation of the corresponding argument in a parameter list. If the value of the argument is `null`, the format item is replaced with . For example, the following call to the method includes a format string with three format items, {0}, {1}, and {2}, and an argument list with three items. +Each overload of the method uses the [composite formatting feature](../../standard/base-types/composite-formatting.md) to include zero-based indexed placeholders, called *format items*, in a composite format string. At runtime, each format item is replaced with the string representation of the corresponding argument in a parameter list. If the value of the argument is `null`, the format item is replaced with . For example, the following call to the method includes a format string with three format items, {0}, {1}, and {2}, and an argument list with three items. :::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/formatoverload1.cs" id="Snippet8"::: :::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/formatoverload1.fs" id="Snippet8"::: @@ -174,23 +174,23 @@ The following example uses the `width` and `formatString` arguments to produce f ## How arguments are formatted -Format items are processed sequentially from the beginning of the string. Each format item has an index that corresponds to an object in the method's argument list. The method retrieves the argument and derives its string representation as follows: +Format items are processed sequentially from the beginning of the string. Each format item has an index that corresponds to an object in the method's argument list. The method retrieves the argument and derives its string representation as follows: - If the argument is `null`, the method inserts into the result string. You don't have to be concerned with handling a for null arguments. -- If you call the overload and the `provider` object's implementation returns a non-null implementation, the argument is passed to its method. If the format item includes a `formatString` argument, it is passed as the first argument to the method. If the implementation is available and produces a non-null string, that string is returned as the string representation of the argument; otherwise, the next step executes. +- If you call the overload and the `provider` object's implementation returns a non-null implementation, the argument is passed to its method. If the format item includes a `formatString` argument, it is passed as the first argument to the method. If the implementation is available and produces a non-null string, that string is returned as the string representation of the argument; otherwise, the next step executes. -- If the argument implements the interface, its implementation is called. +- If the argument implements the interface, its implementation is called. - The argument's parameterless `ToString` method, which either overrides or inherits from a base class implementation, is called. -For an example that intercepts calls to the method and allows you to see what information the method passes to a formatting method for each format item in a composite format string, see [Example: An intercept provider and Roman numeral formatter](#example-an-intercept-provider-and-roman-numeral-formatter). +For an example that intercepts calls to the method and allows you to see what information the method passes to a formatting method for each format item in a composite format string, see [Example: An intercept provider and Roman numeral formatter](#example-an-intercept-provider-and-roman-numeral-formatter). For more information, see [Processing order](../../standard/base-types/composite-formatting.md#processing-order). ## Format items that have the same index -The method throws a exception if the index of an index item is greater than or equal to the number of arguments in the argument list. However, `format` can include more format items than there are arguments, as long as multiple format items have the same index. In the call to the method in following example, the argument list has a single argument, but the format string includes two format items: one displays the decimal value of a number, and the other displays its hexadecimal value. +The method throws a exception if the index of an index item is greater than or equal to the number of arguments in the argument list. However, `format` can include more format items than there are arguments, as long as multiple format items have the same index. In the call to the method in following example, the argument list has a single argument, but the format string includes two format items: one displays the decimal value of a number, and the other displays its hexadecimal value. :::code language="csharp" source="./snippets/System/String/Format/csharp/Example1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/String/Format/fsharp/Example1.fs" id="Snippet1"::: @@ -198,17 +198,17 @@ The method throws a ## Format and culture -Generally, objects in the argument list are converted to their string representations by using the conventions of the current culture, which is returned by the property. You can control this behavior by calling one of the overloads of that includes a `provider` parameter. The `provider` parameter is an implementation that supplies custom and culture-specific formatting information that is used to moderate the formatting process. +Generally, objects in the argument list are converted to their string representations by using the conventions of the current culture, which is returned by the property. You can control this behavior by calling one of the overloads of that includes a `provider` parameter. The `provider` parameter is an implementation that supplies custom and culture-specific formatting information that is used to moderate the formatting process. -The interface has a single member, , which is responsible for returning the object that provides formatting information. .NET has three implementations that provide culture-specific formatting: +The interface has a single member, , which is responsible for returning the object that provides formatting information. .NET has three implementations that provide culture-specific formatting: -- . Its method returns a culture-specific object for formatting numeric values and a culture-specific object for formatting date and time values. -- , which is used for culture-specific formatting of date and time values. Its method returns itself. +- . Its method returns a culture-specific object for formatting numeric values and a culture-specific object for formatting date and time values. +- , which is used for culture-specific formatting of date and time values. Its method returns itself. - , which is used for culture-specific formatting of numeric values. Its method returns itself. ## Custom formatting operations -You can also call the any of the overloads of the method that have a `provider` parameter of type to perform custom formatting operations. For example, you could format an integer as an identification number or as a telephone number. To perform custom formatting, your `provider` argument must implement both the and interfaces. When the method is passed an implementation as the `provider` argument, the method calls its implementation and requests an object of type . It then calls the returned object's method to format each format item in the composite string passed to it. +You can also call the any of the overloads of the method that have a `provider` parameter of type to perform custom formatting operations. For example, you could format an integer as an identification number or as a telephone number. To perform custom formatting, your `provider` argument must implement both the and interfaces. When the method is passed an implementation as the `provider` argument, the method calls its implementation and requests an object of type . It then calls the returned object's method to format each format item in the composite string passed to it. For more information about providing custom formatting solutions, see [How to: Define and Use Custom Numeric Format Providers](../../standard/base-types/how-to-define-and-use-custom-numeric-format-providers.md) and . For an example that converts integers to formatted custom numbers, see [Example: A custom formatting operation](#example-a-custom-formatting-operation). For an example that converts unsigned bytes to Roman numerals, see [Example: An intercept provider and Roman numeral formatter](#example-an-intercept-provider-and-roman-numeral-formatter). @@ -224,7 +224,7 @@ This example defines a format provider that formats an integer value as a custom This example defines a custom format provider that implements the and interfaces to do two things: -- It displays the parameters passed to its implementation. This enables us to see what parameters the method is passing to the custom formatting implementation for each object that it tries to format. This can be useful when you're debugging your application. +- It displays the parameters passed to its implementation. This enables us to see what parameters the method is passing to the custom formatting implementation for each object that it tries to format. This can be useful when you're debugging your application. - If the object to be formatted is an unsigned byte value that is to be formatted by using the "R" standard format string, the custom formatter formats the numeric value as a Roman numeral. :::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/interceptor2.cs" id="Snippet11"::: @@ -237,7 +237,7 @@ This example defines a custom format provider that implements the method or another method that supports composite formatting, such as or . +- More flexible. It can be used in any string without requiring a call to a method that supports composite formatting. Otherwise, you have to call the method or another method that supports composite formatting, such as or . - More readable. Because the expression to insert into a string appears in the interpolated expression rather than in a argument list, interpolated strings are easier to code and to read. Interpolated strings can also be used in string concatenation operations to produce more concise, clearer code. A comparison of the following two code examples illustrates the superiority of interpolated strings over string concatenation and calls to composite formatting methods. The use of multiple string concatenation operations in the following example produces verbose and hard-to-read code. @@ -246,7 +246,7 @@ A comparison of the following two code examples illustrates the superiority of i :::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa-interpolated1.fs" id="SnippetQAInterpolated"::: :::code language="vb" source="./snippets/System/String/Format/vb/qa-interpolated1.vb"::: -In contrast, the use of interpolated strings in the following example produces much clearer, more concise code than the string concatenation statement and the call to the method in the previous example. +In contrast, the use of interpolated strings in the following example produces much clearer, more concise code than the string concatenation statement and the call to the method in the previous example. :::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa-interpolated2.cs" id="SnippetQAInterpolated2"::: :::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa-interpolated2.fs" id="SnippetQAInterpolated2"::: diff --git a/docs/fundamentals/runtime-libraries/system-string-intern.md b/docs/fundamentals/runtime-libraries/system-string-intern.md index 5f2d30973d839..a56be6242e76b 100644 --- a/docs/fundamentals/runtime-libraries/system-string-intern.md +++ b/docs/fundamentals/runtime-libraries/system-string-intern.md @@ -13,9 +13,9 @@ dev_langs: The common language runtime conserves string storage by maintaining a table, called the *intern pool*, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system. For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable. -The method uses the intern pool to search for a string equal to the value of its parameter, `str`. If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to `str` is added to the intern pool, then that reference is returned. (In contrast, the method returns a null reference if the requested string doesn't exist in the intern pool.) +The method uses the intern pool to search for a string equal to the value of its parameter, `str`. If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to `str` is added to the intern pool, then that reference is returned. (In contrast, the method returns a null reference if the requested string doesn't exist in the intern pool.) -In the following example, the string `s1`, which has a value of "MyTest", is already interned because it is a literal in the program. The class generates a new string object that has the same value as `s1`. A reference to that string is assigned to `s2`. The method searches for a string that has the same value as `s2`. Because such a string exists, the method returns the same reference that's assigned to `s1`. That reference is then assigned to `s3`. References `s1` and `s2` compare unequal because they refer to different objects; references `s1` and `s3` compare equal because they refer to the same string. +In the following example, the string `s1`, which has a value of "MyTest", is already interned because it is a literal in the program. The class generates a new string object that has the same value as `s1`. A reference to that string is assigned to `s2`. The method searches for a string that has the same value as `s2`. Because such a string exists, the method returns the same reference that's assigned to `s1`. That reference is then assigned to `s3`. References `s1` and `s2` compare unequal because they refer to different objects; references `s1` and `s3` compare equal because they refer to the same string. :::code language="csharp" source="./snippets/System/String/Intern/csharp/Intern1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/String/Intern/fsharp/Intern1.fs" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-string-isnullorempty.md b/docs/fundamentals/runtime-libraries/system-string-isnullorempty.md index 0b4dff872ef9c..d93d6209a3502 100644 --- a/docs/fundamentals/runtime-libraries/system-string-isnullorempty.md +++ b/docs/fundamentals/runtime-libraries/system-string-isnullorempty.md @@ -11,13 +11,13 @@ dev_langs: [!INCLUDE [context](includes/context.md)] - is a convenience method that enables you to simultaneously test whether a is `null` or its value is . It is equivalent to the following code: + is a convenience method that enables you to simultaneously test whether a is `null` or its value is . It is equivalent to the following code: :::code language="csharp" source="./snippets/System/String/IsNullOrEmpty/csharp/isnullorempty1.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System/String/IsNullOrEmpty/vb/isnullorempty1.vb" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/String/IsNullOrEmpty/fsharp/isnullorempty1.fs" id="Snippet1"::: -You can use the method to test whether a string is `null`, its value is , or it consists only of white-space characters. +You can use the method to test whether a string is `null`, its value is , or it consists only of white-space characters. ## What is a null string? @@ -29,7 +29,7 @@ A string is `null` if it has not been assigned a value (in C++ and Visual Basic) ## What is an empty string? -A string is empty if it is explicitly assigned an empty string ("") or . An empty string has a of 0. The following example creates an empty string and displays its value and its length. +A string is empty if it is explicitly assigned an empty string ("") or . An empty string has a of 0. The following example creates an empty string and displays its value and its length. :::code language="csharp" source="./snippets/System/String/IsNullOrEmpty/csharp/NullString1.cs" id="Snippet3"::: :::code language="vb" source="./snippets/System/String/IsNullOrEmpty/vb/NullString1.vb" id="Snippet3"::: diff --git a/docs/fundamentals/runtime-libraries/system-string.md b/docs/fundamentals/runtime-libraries/system-string.md index 486d52f837345..ee28def0c1f37 100644 --- a/docs/fundamentals/runtime-libraries/system-string.md +++ b/docs/fundamentals/runtime-libraries/system-string.md @@ -25,7 +25,7 @@ You can instantiate a object in the following ways: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/program.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/String/Overview/vb/instantiate1.vb" id="Snippet1"::: -- By calling a class constructor. The following example instantiates strings by calling several class constructors. Note that some of the constructors include pointers to character arrays or signed byte arrays as parameters. Visual Basic does not support calls to these constructors. For detailed information about constructors, see the constructor summary. +- By calling a class constructor. The following example instantiates strings by calling several class constructors. Note that some of the constructors include pointers to character arrays or signed byte arrays as parameters. Visual Basic does not support calls to these constructors. For detailed information about constructors, see the constructor summary. :::code language="csharp" source="./snippets/System/String/Overview/csharp/program.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/program.fs" id="Snippet2"::: @@ -64,7 +64,7 @@ A single object usually represents a single code point; that :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/grapheme1.fs" id="Snippet2"::: :::code language="vb" source="./snippets/System/String/Overview/vb/grapheme1.vb" id="Snippet2"::: -- A Unicode supplementary code point (a surrogate pair) is represented by a object whose code point is a high surrogate followed by a object whose code point is a low surrogate. The code units of high surrogates range from U+D800 to U+DBFF. The code units of low surrogates range from U+DC00 to U+DFFF. Surrogate pairs are used to represent characters in the 16 Unicode supplementary planes. The following example creates a surrogate character and passes it to the method to determine whether it is a surrogate pair. +- A Unicode supplementary code point (a surrogate pair) is represented by a object whose code point is a high surrogate followed by a object whose code point is a low surrogate. The code units of high surrogates range from U+D800 to U+DBFF. The code units of low surrogates range from U+DC00 to U+DFFF. Surrogate pairs are used to represent characters in the 16 Unicode supplementary planes. The following example creates a surrogate character and passes it to the method to determine whether it is a surrogate pair. :::code language="csharp" source="./snippets/System/String/Overview/csharp/surrogate1.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/surrogate1.fs" id="Snippet3"::: @@ -74,7 +74,7 @@ A single object usually represents a single code point; that Characters in a string are represented by UTF-16 encoded code units, which correspond to values. -Each character in a string has an associated Unicode character category, which is represented in .NET by the enumeration. The category of a character or a surrogate pair can be determined by calling the method. +Each character in a string has an associated Unicode character category, which is represented in .NET by the enumeration. The category of a character or a surrogate pair can be determined by calling the method. [!INCLUDE[character-categories](./includes/unicode-categories.md)] @@ -90,19 +90,19 @@ In addition, .NET supports string comparison and sorting based on the Unicode st In .NET, a object can include embedded null characters, which count as a part of the string's length. However, in some languages such as C and C++, a null character indicates the end of a string; it is not considered a part of the string and is not counted as part of the string's length. This means that the following common assumptions that C and C++ programmers or libraries written in C or C++ might make about strings are not necessarily valid when applied to objects: -- The value returned by the `strlen` or `wcslen` functions does not necessarily equal . +- The value returned by the `strlen` or `wcslen` functions does not necessarily equal . - The string created by the `strcpy_s` or `wcscpy_s` functions is not necessarily identical to the string being copied. You should ensure that native C and C++ code that instantiates objects, and code that is passed objects through platform invoke, don't assume that an embedded null character marks the end of the string. -Embedded null characters in a string are also treated differently when a string is sorted (or compared) and when a string is searched. Null characters are ignored when performing culture-sensitive comparisons between two strings, including comparisons using the invariant culture. They are considered only for ordinal or case-insensitive ordinal comparisons. On the other hand, embedded null characters are always considered when searching a string with methods such as , , and . +Embedded null characters in a string are also treated differently when a string is sorted (or compared) and when a string is searched. Null characters are ignored when performing culture-sensitive comparisons between two strings, including comparisons using the invariant culture. They are considered only for ordinal or case-insensitive ordinal comparisons. On the other hand, embedded null characters are always considered when searching a string with methods such as , , and . ## Strings and indexes -An index is the position of a object (not a Unicode character) in a . An index is a zero-based, nonnegative number that starts from the first position in the string, which is index position zero. A number of search methods, such as and , return the index of a character or substring in the string instance. +An index is the position of a object (not a Unicode character) in a . An index is a zero-based, nonnegative number that starts from the first position in the string, which is index position zero. A number of search methods, such as and , return the index of a character or substring in the string instance. -The property lets you access individual objects by their index position in the string. Because the property is the default property (in Visual Basic) or the indexer (in C# and F#), you can access the individual objects in a string by using code such as the following. This code looks for white space or punctuation characters in a string to determine how many words the string contains. +The property lets you access individual objects by their index position in the string. Because the property is the default property (in Visual Basic) or the indexer (in C# and F#), you can access the individual objects in a string by using code such as the following. This code looks for white space or punctuation characters in a string to determine how many words the string contains. :::code language="csharp" source="./snippets/System/String/Overview/csharp/index11.cs" id="Snippet4"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/index11.fs" id="Snippet4"::: @@ -114,35 +114,35 @@ Because the class implements the object. In particular, a string may contain multi-character units of text that are formed by a base character followed by one or more combining characters or by surrogate pairs. To work with Unicode characters instead of objects, use the and classes, or the method and the struct. The following example illustrates the difference between code that works with objects and code that works with Unicode characters. It compares the number of characters or text elements in each word of a sentence. The string includes two sequences of a base character followed by a combining character. +Consecutive index values might not correspond to consecutive Unicode characters, because a Unicode character might be encoded as more than one object. In particular, a string may contain multi-character units of text that are formed by a base character followed by one or more combining characters or by surrogate pairs. To work with Unicode characters instead of objects, use the and classes, or the method and the struct. The following example illustrates the difference between code that works with objects and code that works with Unicode characters. It compares the number of characters or text elements in each word of a sentence. The string includes two sequences of a base character followed by a combining character. :::code language="csharp" source="./snippets/System/String/Overview/csharp/index3.cs" id="Snippet6"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/index3.fs" id="Snippet6"::: :::code language="vb" source="./snippets/System/String/Overview/vb/index3.vb" id="Snippet6"::: -This example works with text elements by using the method and the class to enumerate all the text elements in a string. You can also retrieve an array that contains the starting index of each text element by calling the method. +This example works with text elements by using the method and the class to enumerate all the text elements in a string. You can also retrieve an array that contains the starting index of each text element by calling the method. For more information about working with units of text rather than individual values, see [Introduction to character encoding in .NET](../../standard/base-types/character-encoding-introduction.md). ## Null strings and empty strings -A string that has been declared but has not been assigned a value is `null`. Attempting to call methods on that string throws a . A null string is different from an empty string, which is a string whose value is "" or . In some cases, passing either a null string or an empty string as an argument in a method call throws an exception. For example, passing a null string to the method throws an , and passing an empty string throws a . In other cases, a method argument can be either a null string or an empty string. For example, if you are providing an implementation for a class, you want to equate both a null string and an empty string with the general ("G") format specifier. +A string that has been declared but has not been assigned a value is `null`. Attempting to call methods on that string throws a . A null string is different from an empty string, which is a string whose value is "" or . In some cases, passing either a null string or an empty string as an argument in a method call throws an exception. For example, passing a null string to the method throws an , and passing an empty string throws a . In other cases, a method argument can be either a null string or an empty string. For example, if you are providing an implementation for a class, you want to equate both a null string and an empty string with the general ("G") format specifier. The class includes the following two convenience methods that enable you to test whether a string is `null` or empty: -- , which indicates whether a string is either `null` or is equal to . This method eliminates the need to use code such as the following: +- , which indicates whether a string is either `null` or is equal to . This method eliminates the need to use code such as the following: :::code language="csharp" source="./snippets/System/String/Overview/csharp/nullorempty1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/nullorempty1.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/String/Overview/vb/nullorempty1.vb" id="Snippet1"::: -- , which indicates whether a string is `null`, equals , or consists exclusively of white-space characters. This method eliminates the need to use code such as the following: +- , which indicates whether a string is `null`, equals , or consists exclusively of white-space characters. This method eliminates the need to use code such as the following: :::code language="csharp" source="./snippets/System/String/Overview/csharp/nullorempty1.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/nullorempty1.fs" id="Snippet2"::: :::code language="vb" source="./snippets/System/String/Overview/vb/nullorempty1.vb" id="Snippet2"::: -The following example uses the method in the implementation of a custom `Temperature` class. The method supports the "G", "C", "F", and "K" format strings. If an empty format string or a format string whose value is `null` is passed to the method, its value is changed to the "G" format string. +The following example uses the method in the implementation of a custom `Temperature` class. The method supports the "G", "C", "F", and "K" format strings. If an empty format string or a format string whose value is `null` is passed to the method, its value is changed to the "G" format string. :::code language="csharp" source="./snippets/System/String/Overview/csharp/nullorempty1.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/nullorempty1.fs" id="Snippet3"::: @@ -158,7 +158,7 @@ Because strings are immutable, string manipulation routines that perform repeate :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/immutable.fs" id="Snippet15"::: :::code language="vb" source="./snippets/System/String/Overview/vb/immutable.vb" id="Snippet15"::: -You can use the class instead of the class for operations that make multiple changes to the value of a string. Unlike instances of the class, objects are mutable; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string. When you have finished modifying the value of a object, you can call its method to convert it to a string. The following example replaces the used in the previous example to concatenate 1000 random characters in the range to 0x0001 to 0x052F with a object. +You can use the class instead of the class for operations that make multiple changes to the value of a string. Unlike instances of the class, objects are mutable; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string. When you have finished modifying the value of a object, you can call its method to convert it to a string. The following example replaces the used in the previous example to concatenate 1000 random characters in the range to 0x0001 to 0x052F with a object. :::code language="csharp" source="./snippets/System/String/Overview/csharp/immutable1.cs" id="Snippet16"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/immutable1.fs" id="Snippet16"::: @@ -168,7 +168,7 @@ You can use the class instead of the class perform either ordinal or culture-sensitive (linguistic) operations on a object. An ordinal operation acts on the numeric value of each object. A culture-sensitive operation acts on the value of the object, and takes culture-specific casing, sorting, formatting, and parsing rules into account. Culture-sensitive operations execute in the context of an explicitly declared culture or the implicit current culture. The two kinds of operations can produce very different results when they are performed on the same string. -.NET also supports culture-insensitive linguistic string operations by using the invariant culture (), which is loosely based on the culture settings of the English language independent of region. Unlike other settings, the settings of the invariant culture are guaranteed to remain consistent on a single computer, from system to system, and across versions of .NET. The invariant culture can be seen as a kind of black box that ensures stability of string comparisons and ordering across all cultures. +.NET also supports culture-insensitive linguistic string operations by using the invariant culture (), which is loosely based on the culture settings of the English language independent of region. Unlike other settings, the settings of the invariant culture are guaranteed to remain consistent on a single computer, from system to system, and across versions of .NET. The invariant culture can be seen as a kind of black box that ensures stability of string comparisons and ordering across all cultures. > [!IMPORTANT] > If your application makes a security decision about a symbolic identifier such as a file name or named pipe, or about persisted data such as the text-based data in an XML file, the operation should use an ordinal comparison instead of a culture-sensitive comparison. This is because a culture-sensitive comparison can yield different results depending on the culture in effect, whereas an ordinal comparison depends solely on the binary value of the compared characters. @@ -179,7 +179,7 @@ Members of the class perform either ordinal or culture-sens Operations for casing, parsing and formatting, comparison and sorting, and testing for equality can be either ordinal or culture-sensitive. The following sections discuss each category of operation. > [!TIP] -> You should always call a method overload that makes the intent of your method call clear. For example, instead of calling the method to perform a culture-sensitive comparison of two strings by using the conventions of the current culture, you should call the method with a value of for the `comparisonType` argument. For more information, see [Best Practices for Using Strings](../../standard/base-types/best-practices-strings.md). +> You should always call a method overload that makes the intent of your method call clear. For example, instead of calling the method to perform a culture-sensitive comparison of two strings by using the conventions of the current culture, you should call the method with a value of for the `comparisonType` argument. For more information, see [Best Practices for Using Strings](../../standard/base-types/best-practices-strings.md). You can download the sorting weight tables, a set of text files that contain information on the character weights used in sorting and comparison operations, from the following links: @@ -188,7 +188,7 @@ You can download the sorting weight tables, a set of text files that contain inf ### Casing -Casing rules determine how to change the capitalization of a Unicode character; for example, from lowercase to uppercase. Often, a casing operation is performed before a string comparison. For example, a string might be converted to uppercase so that it can be compared with another uppercase string. You can convert the characters in a string to lowercase by calling the or method, and you can convert them to uppercase by calling the or method. In addition, you can use the method to convert a string to title case. +Casing rules determine how to change the capitalization of a Unicode character; for example, from lowercase to uppercase. Often, a casing operation is performed before a string comparison. For example, a string might be converted to uppercase so that it can be compared with another uppercase string. You can convert the characters in a string to lowercase by calling the or method, and you can convert them to uppercase by calling the or method. In addition, you can use the method to convert a string to title case. [!INCLUDE[platform-note](./includes/c-and-posix-cultures.md)] @@ -248,7 +248,7 @@ Similarly, as the following example shows, a single string can produce different Conventions for comparing and sorting strings vary from culture to culture. For example, the sort order may be based on phonetics or on the visual representation of characters. In East Asian languages, characters are sorted by the stroke and radical of ideographs. Sorting also depends on the order languages and cultures use for the alphabet. For example, the Danish language has an "Æ" character that it sorts after "Z" in the alphabet. In addition, comparisons can be case-sensitive or case-insensitive, and casing rules might differ by culture. Ordinal comparison, on the other hand, uses the Unicode code points of individual characters in a string when comparing and sorting strings. -Sort rules determine the alphabetic order of Unicode characters and how two strings compare to each other. For example, the method compares two strings based on the parameter. If the parameter value is , the method performs a linguistic comparison that uses the conventions of the current culture; if the parameter value is , the method performs an ordinal comparison. Consequently, as the following example shows, if the current culture is U.S. English, the first call to the method (using culture-sensitive comparison) considers "a" less than "A", but the second call to the same method (using ordinal comparison) considers "a" greater than "A". +Sort rules determine the alphabetic order of Unicode characters and how two strings compare to each other. For example, the method compares two strings based on the parameter. If the parameter value is , the method performs a linguistic comparison that uses the conventions of the current culture; if the parameter value is , the method performs an ordinal comparison. Consequently, as the following example shows, if the current culture is U.S. English, the first call to the method (using culture-sensitive comparison) considers "a" less than "A", but the second call to the same method (using ordinal comparison) considers "a" greater than "A". :::code language="csharp" source="./snippets/System/String/Overview/csharp/compare11.cs" id="Snippet10"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/compare11.fs" id="Snippet10"::: @@ -258,13 +258,13 @@ Sort rules determine the alphabetic order of Unicode characters and how two stri - A word sort performs a culture-sensitive comparison of strings in which certain nonalphanumeric Unicode characters might have special weights assigned to them. For example, the hyphen (-) might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. For a list of the methods that compare two strings using word sort rules, see the [String operations by category](#string-operations-by-category) section. -- A string sort also performs a culture-sensitive comparison. It is similar to a word sort, except that there are no special cases, and all nonalphanumeric symbols come before all alphanumeric Unicode characters. Two strings can be compared using string sort rules by calling the method overloads that have an `options` parameter that is supplied a value of . Note that this is the only method that .NET provides to compare two strings using string sort rules. +- A string sort also performs a culture-sensitive comparison. It is similar to a word sort, except that there are no special cases, and all nonalphanumeric symbols come before all alphanumeric Unicode characters. Two strings can be compared using string sort rules by calling the method overloads that have an `options` parameter that is supplied a value of . Note that this is the only method that .NET provides to compare two strings using string sort rules. - An ordinal sort compares strings based on the numeric value of each object in the string. An ordinal comparison is automatically case-sensitive because the lowercase and uppercase versions of a character have different code points. However, if case is not important, you can specify an ordinal comparison that ignores case. This is equivalent to converting the string to uppercase by using the invariant culture and then performing an ordinal comparison on the result. For a list of the methods that compare two strings using ordinal sort rules, see the [String operations by category](#string-operations-by-category) section. -A culture-sensitive comparison is any comparison that explicitly or implicitly uses a object, including the invariant culture that is specified by the property. The implicit culture is the current culture, which is specified by the and properties. There is considerable variation in the sort order of alphabetic characters (that is, characters for which the property returns `true`) across cultures. You can specify a culture-sensitive comparison that uses the conventions of a specific culture by supplying a object to a string comparison method such as . You can specify a culture-sensitive comparison that uses the conventions of the current culture by supplying , , or any member of the enumeration other than or to an appropriate overload of the method. A culture-sensitive comparison is generally appropriate for sorting whereas an ordinal comparison is not. An ordinal comparison is generally appropriate for determining whether two strings are equal (that is, for determining identity) whereas a culture-sensitive comparison is not. +A culture-sensitive comparison is any comparison that explicitly or implicitly uses a object, including the invariant culture that is specified by the property. The implicit culture is the current culture, which is specified by the and properties. There is considerable variation in the sort order of alphabetic characters (that is, characters for which the property returns `true`) across cultures. You can specify a culture-sensitive comparison that uses the conventions of a specific culture by supplying a object to a string comparison method such as . You can specify a culture-sensitive comparison that uses the conventions of the current culture by supplying , , or any member of the enumeration other than or to an appropriate overload of the method. A culture-sensitive comparison is generally appropriate for sorting whereas an ordinal comparison is not. An ordinal comparison is generally appropriate for determining whether two strings are equal (that is, for determining identity) whereas a culture-sensitive comparison is not. -The following example illustrates the difference between culture-sensitive and ordinal comparison. The example evaluates three strings, "Apple", "Æble", and "AEble", using ordinal comparison and the conventions of the da-DK and en-US cultures (each of which is the default culture at the time the method is called). Because the Danish language treats the character "Æ" as an individual letter and sorts it after "Z" in the alphabet, the string "Æble" is greater than "Apple". However, "Æble" is not considered equivalent to "AEble", so "Æble" is also greater than "AEble". The en-US culture doesn't include the letter"Æ" but treats it as equivalent to "AE", which explains why "Æble" is less than "Apple" but equal to "AEble". Ordinal comparison, on the other hand, considers "Apple" to be less than "Æble", and "Æble" to be greater than "AEble". +The following example illustrates the difference between culture-sensitive and ordinal comparison. The example evaluates three strings, "Apple", "Æble", and "AEble", using ordinal comparison and the conventions of the da-DK and en-US cultures (each of which is the default culture at the time the method is called). Because the Danish language treats the character "Æ" as an individual letter and sorts it after "Z" in the alphabet, the string "Æble" is greater than "Apple". However, "Æble" is not considered equivalent to "AEble", so "Æble" is also greater than "AEble". The en-US culture doesn't include the letter"Æ" but treats it as equivalent to "AE", which explains why "Æble" is less than "Apple" but equal to "AEble". Ordinal comparison, on the other hand, considers "Apple" to be less than "Æble", and "Æble" to be greater than "AEble". :::code language="csharp" source="./snippets/System/String/Overview/csharp/compare4.cs" id="Snippet21"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/compare4.fs" id="Snippet21"::: @@ -278,14 +278,14 @@ Use the following general guidelines to choose an appropriate sorting or string - If you want the order of strings to remain unchanged across cultures, you should order them based on the conventions of the invariant culture or use an ordinal comparison. For example, you would use an ordinal sort to organize the names of files, processes, mutexes, or named pipes. -- For a comparison that involves a security decision (such as whether a username is valid), you should always perform an ordinal test for equality by calling an overload of the method. +- For a comparison that involves a security decision (such as whether a username is valid), you should always perform an ordinal test for equality by calling an overload of the method. > [!NOTE] > The culture-sensitive sorting and casing rules used in string comparison depend on the version of the .NET. On .NET Core, string comparison depends on the version of the Unicode Standard supported by the underlying operating system. In .NET Framework 4.5 and later versions running on Windows 8 or later, sorting, casing, normalization, and Unicode character information conform to the Unicode 6.0 standard. On other Windows operating systems, they conform to the Unicode 5.0 standard. For more information about word, string, and ordinal sort rules, see the topic. For additional recommendations on when to use each rule, see [Best Practices for Using Strings](../../standard/base-types/best-practices-strings.md). -Ordinarily, you don't call string comparison methods such as directly to determine the sort order of strings. Instead, comparison methods are called by sorting methods such as or . The following example performs four different sorting operations (word sort using the current culture, word sort using the invariant culture, ordinal sort, and string sort using the invariant culture) without explicitly calling a string comparison method, although they do specify the type of comparison to use. Note that each type of sort produces a unique ordering of strings in its array. +Ordinarily, you don't call string comparison methods such as directly to determine the sort order of strings. Instead, comparison methods are called by sorting methods such as or . The following example performs four different sorting operations (word sort using the current culture, word sort using the invariant culture, ordinal sort, and string sort using the invariant culture) without explicitly calling a string comparison method, although they do specify the type of comparison to use. Note that each type of sort produces a unique ordering of strings in its array. :::code language="csharp" source="./snippets/System/String/Overview/csharp/compare2.cs" id="Snippet12"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/compare2.fs" id="Snippet12"::: @@ -294,16 +294,16 @@ Ordinarily, you don't call string comparison methods such as [!TIP] > Internally, .NET uses sort keys to support culturally sensitive string comparison. Each character in a string is given several categories of sort weights, including alphabetic, case, and diacritic. A sort key, represented by the class, provides a repository of these weights for a particular string. If your app performs a large number of searching or sorting operations on the same set of strings, you can improve its performance by generating and storing sort keys for all the strings that it uses. When a sort or comparison operation is required, you use the sort keys instead of the strings. For more information, see the class. -If you don't specify a string comparison convention, sorting methods such as perform a culture-sensitive, case-sensitive sort on strings. The following example illustrates how changing the current culture affects the order of sorted strings in an array. It creates an array of three strings. First, it sets the `System.Threading.Thread.CurrentThread.CurrentCulture` property to en-US and calls the method. The resulting sort order is based on sorting conventions for the English (United States) culture. Next, the example sets the `System.Threading.Thread.CurrentThread.CurrentCulture` property to da-DK and calls the method again. Notice how the resulting sort order differs from the en-US results because it uses the sorting conventions for Danish (Denmark). +If you don't specify a string comparison convention, sorting methods such as perform a culture-sensitive, case-sensitive sort on strings. The following example illustrates how changing the current culture affects the order of sorted strings in an array. It creates an array of three strings. First, it sets the `System.Threading.Thread.CurrentThread.CurrentCulture` property to en-US and calls the method. The resulting sort order is based on sorting conventions for the English (United States) culture. Next, the example sets the `System.Threading.Thread.CurrentThread.CurrentCulture` property to da-DK and calls the method again. Notice how the resulting sort order differs from the en-US results because it uses the sorting conventions for Danish (Denmark). :::code language="csharp" source="./snippets/System/String/Overview/csharp/sort1.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/sort1.fs" id="Snippet3"::: :::code language="vb" source="./snippets/System/String/Overview/vb/sort1.vb" id="Snippet3"::: > [!WARNING] -> If your primary purpose in comparing strings is to determine whether they are equal, you should call the method. Typically, you should use to perform an ordinal comparison. The method is intended primarily to sort strings. +> If your primary purpose in comparing strings is to determine whether they are equal, you should call the method. Typically, you should use to perform an ordinal comparison. The method is intended primarily to sort strings. -String search methods, such as and , also can perform culture-sensitive or ordinal string comparisons. The following example illustrates the differences between ordinal and culture-sensitive comparisons using the method. A culture-sensitive search in which the current culture is English (United States) considers the substring "oe" to match the ligature "œ". Because a soft hyphen (U+00AD) is a zero-width character, the search treats the soft hyphen as equivalent to and finds a match at the beginning of the string. An ordinal search, on the other hand, does not find a match in either case. +String search methods, such as and , also can perform culture-sensitive or ordinal string comparisons. The following example illustrates the differences between ordinal and culture-sensitive comparisons using the method. A culture-sensitive search in which the current culture is English (United States) considers the substring "oe" to match the ligature "œ". Because a soft hyphen (U+00AD) is a zero-width character, the search treats the soft hyphen as equivalent to and finds a match at the beginning of the string. An ordinal search, on the other hand, does not find a match in either case. :::code language="csharp" source="./snippets/System/String/Overview/csharp/compare3.cs" id="Snippet13"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/compare3.fs" id="Snippet13"::: @@ -311,22 +311,22 @@ String search methods, such as and , also can perform culture-sensitive or ordinal string comparisons to determine whether a character or substring is found in a specified string. +String search methods, such as and , also can perform culture-sensitive or ordinal string comparisons to determine whether a character or substring is found in a specified string. -The search methods in the class that search for an individual character, such as the method, or one of a set of characters, such as the method, all perform an ordinal search. To perform a culture-sensitive search for a character, you must call a method such as or . Note that the results of searching for a character using ordinal and culture-sensitive comparison can be very different. For example, a search for a precomposed Unicode character such as the ligature "Æ" (U+00C6) might match any occurrence of its components in the correct sequence, such as "AE" (U+041U+0045), depending on the culture. The following example illustrates the difference between the and methods when searching for an individual character. The ligature "æ" (U+00E6) is found in the string "aerial" when using the conventions of the en-US culture, but not when using the conventions of the da-DK culture or when performing an ordinal comparison. +The search methods in the class that search for an individual character, such as the method, or one of a set of characters, such as the method, all perform an ordinal search. To perform a culture-sensitive search for a character, you must call a method such as or . Note that the results of searching for a character using ordinal and culture-sensitive comparison can be very different. For example, a search for a precomposed Unicode character such as the ligature "Æ" (U+00C6) might match any occurrence of its components in the correct sequence, such as "AE" (U+041U+0045), depending on the culture. The following example illustrates the difference between the and methods when searching for an individual character. The ligature "æ" (U+00E6) is found in the string "aerial" when using the conventions of the en-US culture, but not when using the conventions of the da-DK culture or when performing an ordinal comparison. :::code language="csharp" source="./snippets/System/String/Overview/csharp/search1.cs" id="Snippet22"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/search1.fs" id="Snippet22"::: :::code language="vb" source="./snippets/System/String/Overview/vb/search1.vb" id="Snippet22"::: -On the other hand, class methods that search for a string rather than a character perform a culture-sensitive search if search options are not explicitly specified by a parameter of type . The sole exception is , which performs an ordinal search. +On the other hand, class methods that search for a string rather than a character perform a culture-sensitive search if search options are not explicitly specified by a parameter of type . The sole exception is , which performs an ordinal search. ### Test for equality -Use the method to determine the relationship of two strings in the sort order. Typically, this is a culture-sensitive operation. In contrast, call the method to test for equality. Because the test for equality usually compares user input with some known string, such as a valid user name, a password, or a file system path, it is typically an ordinal operation. +Use the method to determine the relationship of two strings in the sort order. Typically, this is a culture-sensitive operation. In contrast, call the method to test for equality. Because the test for equality usually compares user input with some known string, such as a valid user name, a password, or a file system path, it is typically an ordinal operation. > [!WARNING] -> It is possible to test for equality by calling the method and determining whether the return value is zero. However, this practice is not recommended. To determine whether two strings are equal, you should call one of the overloads of the method. The preferred overload to call is either the instance method or the static method, because both methods include a parameter that explicitly specifies the type of comparison. +> It is possible to test for equality by calling the method and determining whether the return value is zero. However, this practice is not recommended. To determine whether two strings are equal, you should call one of the overloads of the method. The preferred overload to call is either the instance method or the static method, because both methods include a parameter that explicitly specifies the type of comparison. The following example illustrates the danger of performing a culture-sensitive comparison for equality when an ordinal one should be used instead. In this case, the intent of the code is to prohibit file system access from URLs that begin with "FILE://" or "file://" by performing a case-insensitive comparison of the beginning of a URL with the string "FILE://". However, if a culture-sensitive comparison is performed using the Turkish (Turkey) culture on a URL that begins with "file://", the comparison for equality fails, because the Turkish uppercase equivalent of the lowercase "i" is "İ" instead of "I". As a result, file system access is inadvertently permitted. On the other hand, if an ordinal comparison is performed, the comparison for equality succeeds, and file system access is denied. @@ -348,11 +348,11 @@ The Unicode standard defines a process called normalization that returns one bin An ordinal comparison is a binary comparison of the Unicode scalar value of corresponding objects in each string. The class includes a number of methods that can perform an ordinal comparison, including the following: -- Any overload of the , , , , , and methods that includes a parameter. The method performs an ordinal comparison if you supply a value of or for this parameter. +- Any overload of the , , , , , and methods that includes a parameter. The method performs an ordinal comparison if you supply a value of or for this parameter. -- The overloads of the method. +- The overloads of the method. -- Methods that use ordinal comparison by default, such as , , and . +- Methods that use ordinal comparison by default, such as , , and . - Methods that search for a value or for the elements in a array in a string instance. Such methods include and . @@ -374,23 +374,23 @@ The class provides members for comparing strings, testing s You can compare strings to determine their relative position in the sort order by using the following methods: -- returns an integer that indicates the relationship of one string to a second string in the sort order. +- returns an integer that indicates the relationship of one string to a second string in the sort order. -- returns an integer that indicates the relationship of one string to a second string based on a comparison of their code points. +- returns an integer that indicates the relationship of one string to a second string based on a comparison of their code points. -- returns an integer that indicates the relationship of the current string instance to a second string in the sort order. The method provides the and implementations for the class. +- returns an integer that indicates the relationship of the current string instance to a second string in the sort order. The method provides the and implementations for the class. ### Test strings for equality -You call the method to determine whether two strings are equal. The instance and the static overloads let you specify whether the comparison is culture-sensitive or ordinal, and whether case is considered or ignored. Most tests for equality are ordinal, and comparisons for equality that determine access to a system resource (such as a file system object) should always be ordinal. +You call the method to determine whether two strings are equal. The instance and the static overloads let you specify whether the comparison is culture-sensitive or ordinal, and whether case is considered or ignored. Most tests for equality are ordinal, and comparisons for equality that determine access to a system resource (such as a file system object) should always be ordinal. ### Find characters in a string The class includes two kinds of search methods: -- Methods that return a value to indicate whether a particular substring is present in a string instance. These include the , , and methods. +- Methods that return a value to indicate whether a particular substring is present in a string instance. These include the , , and methods. -- Methods that indicate the starting position of a substring in a string instance. These include the , , , and methods. +- Methods that indicate the starting position of a substring in a string instance. These include the , , , and methods. > [!WARNING] > If you want to search a string for a particular pattern rather than a specific substring, you should use regular expressions. For more information, see [.NET Regular Expressions](../../standard/base-types/regular-expressions.md). @@ -399,43 +399,43 @@ The class includes two kinds of search methods: The class includes the following methods that appear to modify the value of a string: -- inserts a string into the current instance. +- inserts a string into the current instance. -- inserts one or more occurrences of a specified character at the beginning of a string. +- inserts one or more occurrences of a specified character at the beginning of a string. -- inserts one or more occurrences of a specified character at the end of a string. +- inserts one or more occurrences of a specified character at the end of a string. -- deletes a substring from the current instance. +- deletes a substring from the current instance. -- replaces a substring with another substring in the current instance. +- replaces a substring with another substring in the current instance. -- and convert all the characters in a string to lowercase. +- and convert all the characters in a string to lowercase. -- and convert all the characters in a string to uppercase. +- and convert all the characters in a string to uppercase. -- removes all occurrences of a character from the beginning and end of a string. +- removes all occurrences of a character from the beginning and end of a string. -- removes all occurrences of a character from the end of a string. +- removes all occurrences of a character from the end of a string. -- removes all occurrences of a character from the beginning of a string. +- removes all occurrences of a character from the beginning of a string. > [!IMPORTANT] > All string modification methods return a new object. They don't modify the value of the current instance. ### Extract substrings from a string -The method separates a single string into multiple strings. Overloads of the method allow you to specify multiple delimiters, to limit the number of substrings that the method extracts, to trim white space from substrings, and to specify whether empty strings (which occur when delimiters are adjacent) are included among the returned strings. +The method separates a single string into multiple strings. Overloads of the method allow you to specify multiple delimiters, to limit the number of substrings that the method extracts, to trim white space from substrings, and to specify whether empty strings (which occur when delimiters are adjacent) are included among the returned strings. ### Combine strings The following methods can be used for string concatenation: -- combines one or more substrings into a single string. -- concatenates one or more substrings into a single element and adds a separator between each substring. +- combines one or more substrings into a single string. +- concatenates one or more substrings into a single element and adds a separator between each substring. ### Format values -The method uses the composite formatting feature to replace one or more placeholders in a string with the string representation of some object or value. The method is often used to do the following: +The method uses the composite formatting feature to replace one or more placeholders in a string with the string representation of some object or value. The method is often used to do the following: - To embed the string representation of a numeric value in a string. - To embed the string representation of a date and time value in a string. @@ -443,17 +443,17 @@ The method uses the - To embed the string representation of some object that supports the interface in a string. - To right-justify or left-justify a substring in a field within a larger string. -For detailed information about formatting operations and examples, see the overload summary. +For detailed information about formatting operations and examples, see the overload summary. ### Copy a string You can call the following methods to make a copy of a string: -- returns a reference to an existing object. -- copies a portion of a string to a character array. +- returns a reference to an existing object. +- copies a portion of a string to a character array. ### Normalize a string -In Unicode, a single character can have multiple code points. Normalization converts these equivalent characters into the same binary representation. The method performs the normalization, and the method determines whether a string is normalized. +In Unicode, a single character can have multiple code points. Normalization converts these equivalent characters into the same binary representation. The method performs the normalization, and the method determines whether a string is normalized. For more information and an example, see the [Normalization](#normalization) section earlier in this article. diff --git a/docs/fundamentals/runtime-libraries/system-stringcomparer.md b/docs/fundamentals/runtime-libraries/system-stringcomparer.md index 6a287898cbb88..103cf074bd023 100644 --- a/docs/fundamentals/runtime-libraries/system-stringcomparer.md +++ b/docs/fundamentals/runtime-libraries/system-stringcomparer.md @@ -7,7 +7,7 @@ ms.date: 12/31/2023 [!INCLUDE [context](includes/context.md)] -An object derived from the class embodies string-based comparison, equality, and hash code operations that take into account both case and culture-specific comparison rules. You can use the class to create a type-specific comparison to sort the elements in a generic collection. Classes such as , , , and use the class for sorting purposes. +An object derived from the class embodies string-based comparison, equality, and hash code operations that take into account both case and culture-specific comparison rules. You can use the class to create a type-specific comparison to sort the elements in a generic collection. Classes such as , , , and use the class for sorting purposes. A comparison operation that is represented by the class is defined to be either case-sensitive or case-insensitive, and use either word (culture-sensitive) or ordinal (culture-insensitive) comparison rules. For more information about word and ordinal comparison rules, see . diff --git a/docs/fundamentals/runtime-libraries/system-text-encoding-default.md b/docs/fundamentals/runtime-libraries/system-text-encoding-default.md index 0737bcfd733bf..f4d21472d21fe 100644 --- a/docs/fundamentals/runtime-libraries/system-text-encoding-default.md +++ b/docs/fundamentals/runtime-libraries/system-text-encoding-default.md @@ -12,7 +12,7 @@ ms.date: 01/24/2024 ## .NET Framework -In .NET Framework, the property always gets the system's active code page and creates a object that corresponds to it. The active code page may be an ANSI code page, which includes the ASCII character set along with additional characters that vary by code page. Because all encodings based on ANSI code pages lose data, consider using the encoding instead. UTF-8 is often identical in the U+00 to U+7F range, but can encode characters outside the ASCII range without loss. +In .NET Framework, the property always gets the system's active code page and creates a object that corresponds to it. The active code page may be an ANSI code page, which includes the ASCII character set along with additional characters that vary by code page. Because all encodings based on ANSI code pages lose data, consider using the encoding instead. UTF-8 is often identical in the U+00 to U+7F range, but can encode characters outside the ASCII range without loss. ## .NET Core diff --git a/docs/fundamentals/runtime-libraries/system-text-encoding.md b/docs/fundamentals/runtime-libraries/system-text-encoding.md index 5cf5a4598ff84..95b799db8d6ea 100644 --- a/docs/fundamentals/runtime-libraries/system-text-encoding.md +++ b/docs/fundamentals/runtime-libraries/system-text-encoding.md @@ -14,7 +14,7 @@ The class represents a character encoding. Encoding is the process of transforming a set of Unicode characters into a sequence of bytes. In contrast, decoding is the process of transforming a sequence of encoded bytes into a set of Unicode characters. For information about the Unicode Transformation Formats (UTFs) and other encodings supported by , see [Character Encoding in .NET](../../standard/base-types/character-encoding.md). - is intended to operate on Unicode characters instead of arbitrary binary data, such as byte arrays. If you must encode arbitrary binary data into text, you should use a protocol such as uuencode, which is implemented by methods such as . + is intended to operate on Unicode characters instead of arbitrary binary data, such as byte arrays. If you must encode arbitrary binary data into text, you should use a protocol such as uuencode, which is implemented by methods such as . .NET provides the following implementations of the class to support current Unicode encodings and other encodings: @@ -30,11 +30,11 @@ Encoding is the process of transforming a set of Unicode characters into a seque The class is primarily intended to convert between different encodings and Unicode. Often one of the derived Unicode classes is the correct choice for your app. -Use the method to obtain other encodings, and call the method to get a list of all encodings. +Use the method to obtain other encodings, and call the method to get a list of all encodings. ## List of encodings -The following table lists the encodings supported by .NET. It lists each encoding's code page number and the values of the encoding's and properties. A check mark in the **.NET Framework support**, **.NET Core support**, or **.NET 5 and later support** column indicates that the code page is natively supported by that .NET implementation, regardless of the underlying platform. For .NET Framework, the availability of other encodings listed in the table depends on the operating system. For .NET Core and .NET 5 and later versions, other encodings are available by using the class or by deriving from the class. +The following table lists the encodings supported by .NET. It lists each encoding's code page number and the values of the encoding's and properties. A check mark in the **.NET Framework support**, **.NET Core support**, or **.NET 5 and later support** column indicates that the code page is natively supported by that .NET implementation, regardless of the underlying platform. For .NET Framework, the availability of other encodings listed in the table depends on the operating system. For .NET Core and .NET 5 and later versions, other encodings are available by using the class or by deriving from the class. > [!NOTE] > Code pages whose property corresponds to an international standard do not necessarily comply in full with that standard. @@ -182,12 +182,12 @@ The following table lists the encodings supported by .NET. It lists each encodin |65000|utf-7|Unicode (UTF-7)|✓|✓|| |65001|utf-8|Unicode (UTF-8)|✓|✓|✓| -The following example calls the and methods to get the Greek (Windows) code page encoding. It compares the objects returned by the method calls to show that they are equal, and then maps displays the Unicode code point and the corresponding code page value for each character in the Greek alphabet. +The following example calls the and methods to get the Greek (Windows) code page encoding. It compares the objects returned by the method calls to show that they are equal, and then maps displays the Unicode code point and the corresponding code page value for each character in the Greek alphabet. :::code language="csharp" source="./snippets/System.Text/Encoding/Overview/csharp/getencoding1.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System.Text/Encoding/Overview/vb/getencoding1.vb" id="Snippet1"::: -If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, you should use the or the provided by the method or the method, respectively, of a derived class. +If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, you should use the or the provided by the method or the method, respectively, of a derived class. The UTF-16 and the UTF-32 encoders can use the big endian byte order (most significant byte first) or the little endian byte order (least significant byte first). For example, the Latin Capital Letter A (U+0041) is serialized as follows (in hexadecimal): @@ -198,7 +198,7 @@ The UTF-16 and the UTF-32 encoders can use the big endian byte order (most signi It is generally more efficient to store Unicode characters using the native byte order. For example, it is better to use the little endian byte order on little endian platforms, such as Intel computers. -The method retrieves an array of bytes that includes the byte order mark (BOM). If this byte array is prefixed to an encoded stream, it helps the decoder to identify the encoding format used. +The method retrieves an array of bytes that includes the byte order mark (BOM). If this byte array is prefixed to an encoded stream, it helps the decoder to identify the encoding format used. For more information on byte order and the byte order mark, see The Unicode Standard at the [Unicode home page](https://home.unicode.org/). diff --git a/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex-match.md b/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex-match.md index a4c0213bcc9f0..644f96afc648b 100644 --- a/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex-match.md +++ b/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex-match.md @@ -39,7 +39,7 @@ You can determine whether the regular expression pattern has been found in the i ## First or multiple matches -This method returns the first substring found at or after the `startat` character position in `input` that matches the regular expression pattern. You can retrieve subsequent matches by repeatedly calling the returned object's method. You can also retrieve all matches in a single method call by calling the method. +This method returns the first substring found at or after the `startat` character position in `input` that matches the regular expression pattern. You can retrieve subsequent matches by repeatedly calling the returned object's method. You can also retrieve all matches in a single method call by calling the method. ## Time-out exceptions diff --git a/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex.md b/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex.md index 1a36825a9034e..d4e4f0252aa5e 100644 --- a/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex.md +++ b/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex.md @@ -28,13 +28,13 @@ For more information about the regular expression language, see [Regular express ## Regex vs. String methods -The class includes several search and comparison methods that you can use to perform pattern matching with text. For example, the , , and methods determine whether a string instance contains a specified substring; and the , , , and methods return the starting position of a specified substring in a string. Use the methods of the class when you are searching for a specific string. Use the class when you are searching for a specific pattern in a string. For more information and examples, see [.NET Regular Expressions](../../standard/base-types/regular-expressions.md). +The class includes several search and comparison methods that you can use to perform pattern matching with text. For example, the , , and methods determine whether a string instance contains a specified substring; and the , , , and methods return the starting position of a specified substring in a string. Use the methods of the class when you are searching for a specific string. Use the class when you are searching for a specific pattern in a string. For more information and examples, see [.NET Regular Expressions](../../standard/base-types/regular-expressions.md). ## Static vs. instance methods After you define a regular expression pattern, you can provide it to the regular expression engine in either of two ways: -- By instantiating a object that represents the regular expression. To do this, you pass the regular expression pattern to a constructor. A object is immutable; when you instantiate a object with a regular expression, that object's regular expression cannot be changed. +- By instantiating a object that represents the regular expression. To do this, you pass the regular expression pattern to a constructor. A object is immutable; when you instantiate a object with a regular expression, that object's regular expression cannot be changed. - By supplying both the regular expression and the text to search to a `static` (`Shared` in Visual Basic) method. This enables you to use a regular expression without explicitly creating a object. @@ -58,21 +58,21 @@ The regular expression engine must compile a particular pattern before the patte Whether you decide to instantiate a object and call its methods or call static methods, the class offers the following pattern-matching functionality: -- Validation of a match. You call the method to determine whether a match is present. +- Validation of a match. You call the method to determine whether a match is present. -- Retrieval of a single match. You call the method to retrieve a object that represents the first match in a string or in part of a string. Subsequent matches can be retrieved by calling the method. +- Retrieval of a single match. You call the method to retrieve a object that represents the first match in a string or in part of a string. Subsequent matches can be retrieved by calling the method. -- Retrieval of all matches. You call the method to retrieve a object that represents all the matches found in a string or in part of a string. +- Retrieval of all matches. You call the method to retrieve a object that represents all the matches found in a string or in part of a string. -- Replacement of matched text. You call the method to replace matched text. The replacement text can also be defined by a regular expression. In addition, some of the methods include a parameter that enables you to programmatically define the replacement text. +- Replacement of matched text. You call the method to replace matched text. The replacement text can also be defined by a regular expression. In addition, some of the methods include a parameter that enables you to programmatically define the replacement text. -- Creation of a string array that is formed from parts of an input string. You call the method to split an input string at positions that are defined by the regular expression. +- Creation of a string array that is formed from parts of an input string. You call the method to split an input string at positions that are defined by the regular expression. In addition to its pattern-matching methods, the class includes several special-purpose methods: -- The method escapes any characters that may be interpreted as regular expression operators in a regular expression or input string. -- The method removes these escape characters. -- The method creates an assembly that contains predefined regular expressions. .NET contains examples of these special-purpose assemblies in the namespace. +- The method escapes any characters that may be interpreted as regular expression operators in a regular expression or input string. +- The method removes these escape characters. +- The method creates an assembly that contains predefined regular expressions. .NET contains examples of these special-purpose assemblies in the namespace. ## Define a time-out value @@ -84,7 +84,7 @@ How you handle the exception depends on the cause of the exception. If the excep You can set a time-out interval by calling the constructor when you instantiate a regular expression object. For static methods, you can set a time-out interval by calling an overload of a matching method that has a `matchTimeout` parameter. If you do not set a time-out value explicitly, the default time-out value is determined as follows: -- By using the application-wide time-out value, if one exists. Set the application-wide time-out value by calling the method to assign the string representation of a value to the `REGEX_DEFAULT_MATCH_TIMEOUT` property. +- By using the application-wide time-out value, if one exists. Set the application-wide time-out value by calling the method to assign the string representation of a value to the `REGEX_DEFAULT_MATCH_TIMEOUT` property. - By using the value , if no application-wide time-out value has been set. > [!IMPORTANT] @@ -105,7 +105,7 @@ The following example uses a regular expression to check for repeated occurrence :::code language="csharp" source="./snippets/System.Text.RegularExpressions/Regex/Overview/csharp/words.cs" id="Snippet0"::: :::code language="vb" source="./snippets/System.Text.RegularExpressions/Regex/Overview/vb/words.vb" id="Snippet0"::: -The next example illustrates the use of a regular expression to check whether a string either represents a currency value or has the correct format to represent a currency value. In this case, the regular expression is built dynamically from the , , , , and properties for the en-US culture. The resulting regular expression is `^\s*[\+-]?\s?\$?\s?(\d*\.?\d{2}?){1}$`. This regular expression can be interpreted as shown in the following table. +The next example illustrates the use of a regular expression to check whether a string either represents a currency value or has the correct format to represent a currency value. In this case, the regular expression is built dynamically from the , , , , and properties for the en-US culture. The resulting regular expression is `^\s*[\+-]?\s?\$?\s?(\d*\.?\d{2}?){1}$`. This regular expression can be interpreted as shown in the following table. | Pattern | Description | |------------|--------------------------------------------------------------------------------| @@ -126,4 +126,4 @@ In this case, the regular expression assumes that a valid currency string does n :::code language="csharp" source="./snippets/System.Text.RegularExpressions/Regex/Overview/csharp/regex_example1.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System.Text.RegularExpressions/Regex/Overview/vb/regex_example1.vb" id="Snippet1"::: -Because the regular expression in this example is built dynamically, you don't know at design time whether the currency symbol, decimal sign, or positive and negative signs of the specified culture (en-US in this example) might be misinterpreted by the regular expression engine as regular expression language operators. To prevent any misinterpretation, the example passes each dynamically generated string to the method. +Because the regular expression in this example is built dynamically, you don't know at design time whether the currency symbol, decimal sign, or positive and negative signs of the specified culture (en-US in this example) might be misinterpreted by the regular expression engine as regular expression language operators. To prevent any misinterpretation, the example passes each dynamically generated string to the method. diff --git a/docs/fundamentals/runtime-libraries/system-text-rune.md b/docs/fundamentals/runtime-libraries/system-text-rune.md index d44eaaee82ffa..166dd38c48112 100644 --- a/docs/fundamentals/runtime-libraries/system-text-rune.md +++ b/docs/fundamentals/runtime-libraries/system-text-rune.md @@ -25,16 +25,16 @@ Consider using the `Rune` type if your code: If your code iterates through the `char` instances in a `string` or a `ReadOnlySpan`, some of the `char` methods won't work correctly on `char` instances that are in the surrogate range. For example, the following APIs require a scalar value `char` to work correctly: -* -* -* -* -* -* -* -* -* -* +* +* +* +* +* +* +* +* +* +* The following example shows code that won't work correctly if any of the `char` instances are surrogate code points: @@ -81,12 +81,12 @@ CountLettersInString("𐓏𐓘𐓻𐓘𐓻𐓟 𐒻𐓟") Consider using the `Rune` type if your code calls APIs that explicitly operate on surrogate code points, such as the following methods: -* -* -* -* -* -* +* +* +* +* +* +* For example, the following method has special logic to deal with surrogate `char` pairs: @@ -149,9 +149,9 @@ There are several ways to get a `Rune` instance. You can use a constructor to cr All of the constructors throw an `ArgumentException` if the input doesn't represent a valid Unicode scalar value. -There are methods available for callers who don't want exceptions to be thrown on failure. +There are methods available for callers who don't want exceptions to be thrown on failure. -`Rune` instances can also be read from existing input sequences. For instance, given a `ReadOnlySpan` that represents UTF-16 data, the method returns the first `Rune` instance at the beginning of the input span. The method operates similarly, accepting a `ReadOnlySpan` parameter that represents UTF-8 data. There are equivalent methods to read from the end of the span instead of the beginning of the span. +`Rune` instances can also be read from existing input sequences. For instance, given a `ReadOnlySpan` that represents UTF-16 data, the method returns the first `Rune` instance at the beginning of the input span. The method operates similarly, accepting a `ReadOnlySpan` parameter that represents UTF-8 data. There are equivalent methods to read from the end of the span instead of the beginning of the span. ## Query properties of a `Rune` @@ -159,7 +159,7 @@ To get the integer code point value of a `Rune` instance, use the and are equivalents to and methods. The `Rune` methods correctly handle surrogate pairs. +Many of the static APIs available on the `char` type are also available on the `Rune` type. For instance, and are equivalents to and methods. The `Rune` methods correctly handle surrogate pairs. The following example code takes a `ReadOnlySpan` as input and trims from both the start and the end of the span every `Rune` that isn't a letter or a digit. @@ -168,13 +168,13 @@ The following example code takes a `ReadOnlySpan` as input and trims from There are some API differences between `char` and `Rune`. For example: * There is no `Rune` equivalent to , since `Rune` instances by definition can never be surrogate code points. -* The doesn't always return the same result as . It does return the same value as . For more information, see the **Remarks** on . +* The doesn't always return the same result as . It does return the same value as . For more information, see the **Remarks** on . ## Convert a `Rune` to UTF-8 or UTF-16 Since a `Rune` is a Unicode scalar value, it can be converted to UTF-8, UTF-16, or UTF-32 encoding. The `Rune` type has built-in support for conversion to UTF-8 and UTF-16. -The converts a `Rune` instance to `char` instances. To query the number of `char` instances that would result from converting a `Rune` instance to UTF-16, use the property. Similar methods exist for UTF-8 conversion. +The converts a `Rune` instance to `char` instances. To query the number of `char` instances that would result from converting a `Rune` instance to UTF-16, use the property. Similar methods exist for UTF-8 conversion. The following example converts a `Rune` instance to a `char` array. The code assumes you have a `Rune` instance in the `rune` variable: @@ -188,7 +188,7 @@ The following example converts a `Rune` instance to a `UTF-8` byte array: :::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/EncodeRune.cs" id="SnippetUtf8ByteArray"::: -The and methods return the actual number of elements written. They throw an exception if the destination buffer is too short to contain the result. There are non-throwing and methods as well for callers who want to avoid exceptions. +The and methods return the actual number of elements written. They throw an exception if the destination buffer is too short to contain the result. There are non-throwing and methods as well for callers who want to avoid exceptions. ## Rune in .NET vs. other languages diff --git a/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md b/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md index 2d66e2a5cfad1..f4afc0aa8c58c 100644 --- a/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md +++ b/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md @@ -17,7 +17,7 @@ The class represents a string-like object whose Although and both represent sequences of characters, they are implemented differently. is an immutable type. That is, each operation that appears to modify a object actually creates a new string. -For example, the call to the method in the following C# example appears to change the value of a string variable named `value`. In fact, the method returns a `value` object that has a different value and address from the `value` object that was passed to the method. Note that the example must be compiled using the `/unsafe` compiler option. +For example, the call to the method in the following C# example appears to change the value of a string variable named `value`. In fact, the method returns a `value` object that has a different value and address from the `value` object that was passed to the method. Note that the example must be compiled using the `/unsafe` compiler option. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/immutability2.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/immutability2.fs" id="Snippet1"::: @@ -42,7 +42,7 @@ Consider using the class under these conditions The property indicates the number of characters the object currently contains. If you add characters to the object, its length increases until it equals the size of the property, which defines the number of characters that the object can contain. If the number of added characters causes the length of the object to exceed its current capacity, new memory is allocated, the value of the property is doubled, new characters are added to the object, and its property is adjusted. Additional memory for the object is allocated dynamically until it reaches the value defined by the property. When the maximum capacity is reached, no further memory can be allocated for the object, and trying to add characters or expand it beyond its maximum capacity throws either an or an exception. -The following example illustrates how a object allocates new memory and increases its capacity dynamically as the string assigned to the object expands. The code creates a object by calling its default (parameterless) constructor. The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. Appending the string "This is a sentence." results in a new memory allocation because the string length (19 characters) exceeds the default capacity of the object. The capacity of the object doubles to 32 characters, the new string is added, and the length of the object now equals 19 characters. The code then appends the string "This is an additional sentence." to the value of the object 11 times. Whenever the append operation causes the length of the object to exceed its capacity, its existing capacity is doubled and the operation succeeds. +The following example illustrates how a object allocates new memory and increases its capacity dynamically as the string assigned to the object expands. The code creates a object by calling its default (parameterless) constructor. The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. Appending the string "This is a sentence." results in a new memory allocation because the string length (19 characters) exceeds the default capacity of the object. The capacity of the object doubles to 32 characters, the new string is added, and the length of the object now equals 19 characters. The code then appends the string "This is an additional sentence." to the value of the object 11 times. Whenever the append operation causes the length of the object to exceed its capacity, its existing capacity is doubled and the operation succeeds. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/default1.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/default1.fs" id="Snippet3"::: @@ -50,17 +50,17 @@ The following example illustrates how a object ## Memory allocation -The default capacity of a object is 16 characters, and its default maximum capacity is . These default values are used if you call the and constructors. +The default capacity of a object is 16 characters, and its default maximum capacity is . These default values are used if you call the and constructors. You can explicitly define the initial capacity of a object in the following ways: - By calling any of the constructors that includes a `capacity` parameter when you create the object. - By explicitly assigning a new value to the property to expand an existing object. (The property throws an exception if the new capacity is less than the existing capacity or greater than the object's maximum capacity.) -- By calling the method with the new capacity. The new capacity must not be greater than the object's maximum capacity. However, unlike an assignment to the property, does not throw an exception if the desired new capacity is less than the existing capacity. In this case, the method call has no effect. +- By calling the method with the new capacity. The new capacity must not be greater than the object's maximum capacity. However, unlike an assignment to the property, does not throw an exception if the desired new capacity is less than the existing capacity. In this case, the method call has no effect. If the length of the string assigned to the object in the constructor call exceeds either the default capacity or the specified capacity, the property is set to the length of the string specified with the `value` parameter. -You can explicitly define the maximum capacity of a object by calling the constructor. You can't change the maximum capacity by assigning a new value to the property, because it is read-only. +You can explicitly define the maximum capacity of a object by calling the constructor. You can't change the maximum capacity by assigning a new value to the property, because it is read-only. As the previous section shows, whenever the existing capacity is inadequate, additional memory is allocated and the capacity of a object doubles up to the value defined by the property. @@ -71,16 +71,16 @@ In general, the default capacity and maximum capacity are adequate for most apps ## Instantiate a StringBuilder object -You instantiate a object by calling one of its six overloaded class constructors, which are listed in the following table. Three of the constructors instantiate a object whose value is an empty string, but set its and values differently. The remaining three constructors define a object that has a specific string value and capacity. Two of the three constructors use the default maximum capacity of , whereas the third allows you to set the maximum capacity. +You instantiate a object by calling one of its six overloaded class constructors, which are listed in the following table. Three of the constructors instantiate a object whose value is an empty string, but set its and values differently. The remaining three constructors define a object that has a specific string value and capacity. Two of the three constructors use the default maximum capacity of , whereas the third allows you to set the maximum capacity. | Constructor | String value | Capacity | Maximum capacity | |-------------|--------------|----------|------------------| |||16|| -|||Defined by the `capacity` parameter|| -|||Defined by the `capacity` parameter|Defined by the `maxCapacity` parameter| -||Defined by the `value` parameter|16 or `value`. , whichever is greater|| -||Defined by the `value` parameter|Defined by the `capacity` parameter or `value`. , whichever is greater.|| -||Defined by `value`. (`startIndex`, `length`)|Defined by the `capacity` parameter or `value`. , whichever is greater.|| +|||Defined by the `capacity` parameter|| +|||Defined by the `capacity` parameter|Defined by the `maxCapacity` parameter| +||Defined by the `value` parameter|16 or `value`. , whichever is greater|| +||Defined by the `value` parameter|Defined by the `capacity` parameter or `value`. , whichever is greater.|| +||Defined by `value`. (`startIndex`, `length`)|Defined by the `capacity` parameter or `value`. , whichever is greater.|| The following example uses three of these constructor overloads to instantiate objects. @@ -110,9 +110,9 @@ You can use the methods of the class to iterate ### Iterate StringBuilder characters -You can access the characters in a object by using the property. In C#, is an indexer; in Visual Basic, it is the default property of the class. This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the property. Characters in a object begin at index 0 (zero) and continue to index - 1. +You can access the characters in a object by using the property. In C#, is an indexer; in Visual Basic, it is the default property of the class. This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the property. Characters in a object begin at index 0 (zero) and continue to index - 1. -The following example illustrates the property. It appends ten random numbers to a object, and then iterates each character. If the character's Unicode category is , it decreases the number by 1 (or changes the number to 9 if its value is 0). The example displays the contents of the object both before and after the values of individual characters were changed. +The following example illustrates the property. It appends ten random numbers to a object, and then iterates each character. If the character's Unicode category is , it decreases the number by 1 (or changes the number to 9 if its value is 0). The example displays the contents of the object both before and after the values of individual characters were changed. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/chars1.cs" id="Snippet7"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/chars1.fs" id="Snippet7"::: @@ -124,15 +124,15 @@ The following example illustrates the The class includes the following methods for expanding the contents of a object: -- The method appends a string, a substring, a character array, a portion of a character array, a single character repeated multiple times, or the string representation of a primitive data type to a object. +- The method appends a string, a substring, a character array, a portion of a character array, a single character repeated multiple times, or the string representation of a primitive data type to a object. -- The method appends a line terminator or a string along with a line terminator to a object. +- The method appends a line terminator or a string along with a line terminator to a object. -- The method appends a [composite format string](../../standard/base-types/composite-formatting.md) to a object. The string representations of objects included in the result string can reflect the formatting conventions of the current system culture or a specified culture. +- The method appends a [composite format string](../../standard/base-types/composite-formatting.md) to a object. The string representations of objects included in the result string can reflect the formatting conventions of the current system culture or a specified culture. -- The method inserts a string, a substring, multiple repetitions of a string, a character array, a portion of a character array, or the string representation of a primitive data type at a specified position in the object. The position is defined by a zero-based index. +- The method inserts a string, a substring, multiple repetitions of a string, a character array, a portion of a character array, or the string representation of a primitive data type at a specified position in the object. The position is defined by a zero-based index. -The following example uses the , , , and methods to expand the text of a object. +The following example uses the , , , and methods to expand the text of a object. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/expand1.cs" id="Snippet9"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/expand1.fs" id="Snippet9"::: @@ -140,9 +140,9 @@ The following example uses the , class includes methods that can reduce the size of the current instance. The method removes all characters and sets the property to zero. The method deletes a specified number of characters starting at a particular index position. In addition, you can remove characters from the end of a object by setting its property to a value that is less than the length of the current instance. +The class includes methods that can reduce the size of the current instance. The method removes all characters and sets the property to zero. The method deletes a specified number of characters starting at a particular index position. In addition, you can remove characters from the end of a object by setting its property to a value that is less than the length of the current instance. -The following example removes some of the text from a object, displays its resulting capacity, maximum capacity, and length property values, and then calls the method to remove all the characters from the object. +The following example removes some of the text from a object, displays its resulting capacity, maximum capacity, and length property values, and then calls the method to remove all the characters from the object. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/delete1.cs" id="Snippet10"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/delete1.fs" id="Snippet10"::: @@ -150,7 +150,7 @@ The following example removes some of the text from a method replaces all occurrences of a character or a string in the entire object or in a particular character range. The following example uses the method to replace all exclamation points (!) with question marks (?) in the object. +The method replaces all occurrences of a character or a string in the entire object or in a particular character range. The following example uses the method to replace all exclamation points (!) with question marks (?) in the object. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/replace1.cs" id="Snippet11"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/replace1.fs" id="Snippet11"::: @@ -158,13 +158,13 @@ The met ## Search the text in a StringBuilder object -The class does not include methods similar to the , , and methods provided by the class, which allow you to search the object for a particular character or a substring. Determining the presence or starting character position of a substring requires that you search a value by using either a string search method or a regular expression method. There are four ways to implement such searches, as the following table shows. +The class does not include methods similar to the , , and methods provided by the class, which allow you to search the object for a particular character or a substring. Determining the presence or starting character position of a substring requires that you search a value by using either a string search method or a regular expression method. There are four ways to implement such searches, as the following table shows. | Technique | Pros | Cons | |-----------|------|------| |Search string values before adding them to the object.|Useful for determining whether a substring exists.|Cannot be used when the index position of a substring is important.| -|Call and search the returned object.|Easy to use if you assign all the text to a object, and then begin to modify it.|Cumbersome to repeatedly call if you must make modifications before all text is added to the object.

You must remember to work from the end of the object's text if you're making changes.| -|Use the property to sequentially search a range of characters.|Useful if you're concerned with individual characters or a small substring.|Cumbersome if the number of characters to search is large or if the search logic is complex.

Results in very poor performance for objects that have grown very large through repeated method calls. | +|Call and search the returned object.|Easy to use if you assign all the text to a object, and then begin to modify it.|Cumbersome to repeatedly call if you must make modifications before all text is added to the object.

You must remember to work from the end of the object's text if you're making changes.| +|Use the property to sequentially search a range of characters.|Useful if you're concerned with individual characters or a small substring.|Cumbersome if the number of characters to search is large or if the search logic is complex.

Results in very poor performance for objects that have grown very large through repeated method calls. | |Convert the object to a object, and perform modifications on the object.|Useful if the number of modifications is small.|Negates the performance benefit of the class if the number of modifications is large.| Let's examine these techniques in greater detail. @@ -175,7 +175,7 @@ Let's examine these techniques in greater detail. :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/pattern1.fs" id="Snippet12"::: :::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/pattern1.vb" id="Snippet12"::: -- Call the method to convert the object to a object. You can search the string by using methods such as or , or you can use regular expressions and the class to search for patterns. Because both and objects use UTF-16 encoding to store characters, the index positions of characters, substrings, and regular expression matches are the same in both objects. This enables you to use methods to make changes at the same position at which that text is found in the object. +- Call the method to convert the object to a object. You can search the string by using methods such as or , or you can use regular expressions and the class to search for patterns. Because both and objects use UTF-16 encoding to store characters, the index positions of characters, substrings, and regular expression matches are the same in both objects. This enables you to use methods to make changes at the same position at which that text is found in the object. > [!NOTE] > If you adopt this approach, you should work from the end of the object to its beginning so that you don't have to repeatedly convert the object to a string. @@ -186,17 +186,17 @@ Let's examine these techniques in greater detail. :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/pattern2.fs" id="Snippet13"::: :::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/pattern2.vb" id="Snippet13"::: -- Use the property to sequentially search a range of characters in a object. This approach might not be practical if the number of characters to be searched is large or the search logic is particularly complex. For the performance implications of character-by-character index-based access for very large, chunked objects, see the documentation for the property. +- Use the property to sequentially search a range of characters in a object. This approach might not be practical if the number of characters to be searched is large or the search logic is particularly complex. For the performance implications of character-by-character index-based access for very large, chunked objects, see the documentation for the property. - The following example is identical in functionality to the previous example but differs in implementation. It uses the property to detect when a character value has changed, inserts an underscore at that position, and converts the first character in the new sequence to uppercase. + The following example is identical in functionality to the previous example but differs in implementation. It uses the property to detect when a character value has changed, inserts an underscore at that position, and converts the first character in the new sequence to uppercase. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/pattern3.cs" id="Snippet14"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/pattern3.fs" id="Snippet14"::: :::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/pattern3.vb" id="Snippet14"::: -- Store all the unmodified text in the object, call the method to convert the object to a object, and perform the modifications on the object. You can use this approach if you have only a few modifications; otherwise, the cost of working with immutable strings might negate the performance benefits of using a object. +- Store all the unmodified text in the object, call the method to convert the object to a object, and perform the modifications on the object. You can use this approach if you have only a few modifications; otherwise, the cost of working with immutable strings might negate the performance benefits of using a object. - The following example is identical in functionality to the previous two examples but differs in implementation. It creates a object, converts it to a object, and then uses a regular expression to perform all remaining modifications on the string. The method uses a lambda expression to perform the replacement on each match. + The following example is identical in functionality to the previous two examples but differs in implementation. It creates a object, converts it to a object, and then uses a regular expression to perform all remaining modifications on the string. The method uses a lambda expression to perform the replacement on each match. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/pattern4.cs" id="Snippet15"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/pattern4.fs" id="Snippet15"::: @@ -204,4 +204,4 @@ Let's examine these techniques in greater detail. ## Convert the StringBuilder object to a string -You must convert the object to a object before you can pass the string represented by the object to a method that has a parameter or display it in the user interface. You perform this conversion by calling the method. For an illustration, see the previous example, which calls the method to convert a object to a string so that it can be passed to a regular expression method. +You must convert the object to a object before you can pass the string represented by the object to a method that has a parameter or display it in the user interface. You perform this conversion by calling the method. For an illustration, see the previous example, which calls the method to convert a object to a string so that it can be passed to a regular expression method. diff --git a/docs/fundamentals/runtime-libraries/system-threading-monitor-wait.md b/docs/fundamentals/runtime-libraries/system-threading-monitor-wait.md index 3f616394960c0..b5e55df8dea7d 100644 --- a/docs/fundamentals/runtime-libraries/system-threading-monitor-wait.md +++ b/docs/fundamentals/runtime-libraries/system-threading-monitor-wait.md @@ -13,21 +13,21 @@ This method does not return until it reacquires an exclusive lock on the `obj` p The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations. -The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the or method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the method again. +The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the or method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the method again. -When a thread calls `Wait`, it releases the lock and enters the waiting queue. At this point, the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked `Wait` remains in the waiting queue until either a thread that holds the lock invokes , or it is the next in the queue and a thread that holds the lock invokes . However, if `millisecondsTimeout` elapses before another thread invokes this object's or method, the original thread is moved to the ready queue in order to regain the lock. +When a thread calls `Wait`, it releases the lock and enters the waiting queue. At this point, the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked `Wait` remains in the waiting queue until either a thread that holds the lock invokes , or it is the next in the queue and a thread that holds the lock invokes . However, if `millisecondsTimeout` elapses before another thread invokes this object's or method, the original thread is moved to the ready queue in order to regain the lock. > [!NOTE] -> If is specified for the `millisecondsTimeout` parameter, this method blocks indefinitely unless the holder of the lock calls or . If `millisecondsTimeout` equals 0, the thread that calls `Wait` releases the lock and then immediately enters the ready queue in order to regain the lock. +> If is specified for the `millisecondsTimeout` parameter, this method blocks indefinitely unless the holder of the lock calls or . If `millisecondsTimeout` equals 0, the thread that calls `Wait` releases the lock and then immediately enters the ready queue in order to regain the lock. -The caller executes `Wait` once, regardless of the number of times has been invoked for the specified object. Conceptually, the `Wait` method stores the number of times the caller invoked on the object and invokes as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls as many times as necessary to restore the saved count for the caller. Calling `Wait` releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released. +The caller executes `Wait` once, regardless of the number of times has been invoked for the specified object. Conceptually, the `Wait` method stores the number of times the caller invoked on the object and invokes as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls as many times as necessary to restore the saved count for the caller. Calling `Wait` releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released. > [!NOTE] > A synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. -The , , and `Wait` methods must be invoked from within a synchronized block of code. +The , , and `Wait` methods must be invoked from within a synchronized block of code. -The remarks for the method explain what happens if is called when no threads are waiting. +The remarks for the method explain what happens if is called when no threads are waiting. ## method @@ -35,26 +35,26 @@ This method does not return until it reacquires an exclusive lock on the `obj` p The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations. -The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the or method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the method again. +The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the or method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the method again. -When a thread calls `Wait`, it releases the lock and enters the waiting queue. At this point, the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked `Wait` remains in the waiting queue until either a thread that holds the lock invokes , or it is the next in the queue and a thread that holds the lock invokes . However, if `timeout` milliseconds elapse before another thread invokes this object's or method, the original thread is moved to the ready queue in order to regain the lock. +When a thread calls `Wait`, it releases the lock and enters the waiting queue. At this point, the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked `Wait` remains in the waiting queue until either a thread that holds the lock invokes , or it is the next in the queue and a thread that holds the lock invokes . However, if `timeout` milliseconds elapse before another thread invokes this object's or method, the original thread is moved to the ready queue in order to regain the lock. > [!NOTE] -> If a representing -1 millisecond is specified for the `timeout` parameter, this method blocks indefinitely unless the holder of the lock calls or . If `timeout` is 0 milliseconds, the thread that calls `Wait` releases the lock and then immediately enters the ready queue in order to regain the lock. +> If a representing -1 millisecond is specified for the `timeout` parameter, this method blocks indefinitely unless the holder of the lock calls or . If `timeout` is 0 milliseconds, the thread that calls `Wait` releases the lock and then immediately enters the ready queue in order to regain the lock. -The caller executes `Wait` once, regardless of the number of times has been invoked for the specified object. Conceptually, the `Wait` method stores the number of times the caller invoked on the object and invokes as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls as many times as necessary to restore the saved count for the caller. Calling `Wait` releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released. +The caller executes `Wait` once, regardless of the number of times has been invoked for the specified object. Conceptually, the `Wait` method stores the number of times the caller invoked on the object and invokes as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls as many times as necessary to restore the saved count for the caller. Calling `Wait` releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released. > [!NOTE] > A synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. -The , , and `Wait` methods must be invoked from within a synchronized block of code. +The , , and `Wait` methods must be invoked from within a synchronized block of code. -The remarks for the method explain what happens if is called when no threads are waiting. +The remarks for the method explain what happens if is called when no threads are waiting. ## Exit the context -The`exitContext` parameter has no effect unless the method is called from inside a nondefault managed context. This can happen if your thread is inside a call to an instance of a class derived from . Even if you are currently executing a method on a class that is not derived from , like , you can be in a nondefault context if a is on your stack in the current application domain. +The`exitContext` parameter has no effect unless the method is called from inside a nondefault managed context. This can happen if your thread is inside a call to an instance of a class derived from . Even if you are currently executing a method on a class that is not derived from , like , you can be in a nondefault context if a is on your stack in the current application domain. -When your code is executing in a nondefault context, specifying `true` for `exitContext` causes the thread to exit the nondefault managed context (that is, to transition to the default context) before executing the method. It returns to the original nondefault context after the call to the method completes. +When your code is executing in a nondefault context, specifying `true` for `exitContext` causes the thread to exit the nondefault managed context (that is, to transition to the default context) before executing the method. It returns to the original nondefault context after the call to the method completes. -This can be useful when the context-bound class has the attribute applied. In that case, all calls to members of the class are automatically synchronized, and the synchronization domain is the entire body of code for the class. If code in the call stack of a member calls the method and specifies `true` for `exitContext`, the thread exits the synchronization domain, allowing a thread that is blocked on a call to any member of the object to proceed. When the method returns, the thread that made the call must wait to reenter the synchronization domain. +This can be useful when the context-bound class has the attribute applied. In that case, all calls to members of the class are automatically synchronized, and the synchronization domain is the entire body of code for the class. If code in the call stack of a member calls the method and specifies `true` for `exitContext`, the thread exits the synchronization domain, allowing a thread that is blocked on a call to any member of the object to proceed. When the method returns, the thread that made the call must wait to reenter the synchronization domain. diff --git a/docs/fundamentals/runtime-libraries/system-threading-monitor.md b/docs/fundamentals/runtime-libraries/system-threading-monitor.md index 0dae025b5734a..ade1e35bd1a57 100644 --- a/docs/fundamentals/runtime-libraries/system-threading-monitor.md +++ b/docs/fundamentals/runtime-libraries/system-threading-monitor.md @@ -10,7 +10,7 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The class allows you to synchronize access to a region of code by taking and releasing a lock on a particular object by calling the , , and methods. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use the class to ensure that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object. Because the Monitor class has thread affinity, the thread that acquired a lock must release the lock by calling the Monitor.Exit method. +The class allows you to synchronize access to a region of code by taking and releasing a lock on a particular object by calling the , , and methods. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use the class to ensure that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object. Because the Monitor class has thread affinity, the thread that acquired a lock must release the lock by calling the Monitor.Exit method. ## Overview @@ -21,18 +21,18 @@ The class allows you to synchronize access to a - An instance of the class cannot be created; the methods of the class are all static. Each method is passed the synchronized object that controls access to the critical section. > [!NOTE] -> Use the class to lock objects other than strings (that is, reference types other than ), not value types. For details, see the overloads of the method and [The lock object](#the-lock-object) section later in this article. +> Use the class to lock objects other than strings (that is, reference types other than ), not value types. For details, see the overloads of the method and [The lock object](#the-lock-object) section later in this article. The following table describes the actions that can be taken by threads that access synchronized objects: |Action|Description| |------------|-----------------| -|, |Acquires a lock for an object. This action also marks the beginning of a critical section. No other thread can enter the critical section unless it is executing the instructions in the critical section using a different locked object.| -||Releases the lock on an object in order to permit other threads to lock and access the object. The calling thread waits while another thread accesses the object. Pulse signals are used to notify waiting threads about changes to an object's state.| -| (signal), |Sends a signal to one or more waiting threads. The signal notifies a waiting thread that the state of the locked object has changed, and the owner of the lock is ready to release the lock. The waiting thread is placed in the object's ready queue so that it might eventually receive the lock for the object. Once the thread has the lock, it can check the new state of the object to see if the required state has been reached.| -||Releases the lock on an object. This action also marks the end of a critical section protected by the locked object.| +|, |Acquires a lock for an object. This action also marks the beginning of a critical section. No other thread can enter the critical section unless it is executing the instructions in the critical section using a different locked object.| +||Releases the lock on an object in order to permit other threads to lock and access the object. The calling thread waits while another thread accesses the object. Pulse signals are used to notify waiting threads about changes to an object's state.| +| (signal), |Sends a signal to one or more waiting threads. The signal notifies a waiting thread that the state of the locked object has changed, and the owner of the lock is ready to release the lock. The waiting thread is placed in the object's ready queue so that it might eventually receive the lock for the object. Once the thread has the lock, it can check the new state of the object to see if the required state has been reached.| +||Releases the lock on an object. This action also marks the end of a critical section protected by the locked object.| -There are two sets of overloads for the and methods. One set of overloads has a `ref` (in C#) or `ByRef` (in Visual Basic) parameter that is atomically set to `true` if the lock is acquired, even if an exception is thrown when acquiring the lock. Use these overloads if it is critical to release the lock in all cases, even when the resources the lock is protecting might not be in a consistent state. +There are two sets of overloads for the and methods. One set of overloads has a `ref` (in C#) or `ByRef` (in Visual Basic) parameter that is atomically set to `true` if the lock is acquired, even if an exception is thrown when acquiring the lock. Use these overloads if it is critical to release the lock in all cases, even when the resources the lock is protecting might not be in a consistent state. ## The lock object @@ -42,16 +42,16 @@ The Monitor class consists of `static` (`Shared` in Visual Basic) methods that o - A reference to a ready queue, which contains the threads that are ready to obtain the lock. - A reference to a waiting queue, which contains the threads that are waiting for notification of a change in the state of the locked object. - locks objects (that is, reference types), not value types. While you can pass a value type to and , it is boxed separately for each call. Since each call creates a separate object, never blocks, and the code it is supposedly protecting is not really synchronized. In addition, the object passed to is different from the object passed to , so throws exception with the message "Object synchronization method was called from an unsynchronized block of code." + locks objects (that is, reference types), not value types. While you can pass a value type to and , it is boxed separately for each call. Since each call creates a separate object, never blocks, and the code it is supposedly protecting is not really synchronized. In addition, the object passed to is different from the object passed to , so throws exception with the message "Object synchronization method was called from an unsynchronized block of code." The following example illustrates this problem. It launches ten tasks, each of which just sleeps for 250 milliseconds. Each task then updates a counter variable, `nTasks`, which is intended to count the number of tasks that actually launched and executed. Because `nTasks` is a global variable that can be updated by multiple tasks simultaneously, a monitor is used to protect it from simultaneous modification by multiple tasks. However, as the output from the example shows, each of the tasks throws a exception. :::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/badlock1.cs" id="Snippet2"::: :::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/badlock1.vb" id="Snippet2"::: -Each task throws a exception because the `nTasks` variable is boxed before the call to the method in each task. In other words, each method call is passed a separate variable that is independent of the others. `nTasks` is boxed again in the call to the method. Once again, this creates ten new boxed variables, which are independent of each other, `nTasks`, and the ten boxed variables created in the call to the method. The exception is thrown, then, because our code is attempting to release a lock on a newly created variable that was not previously locked. +Each task throws a exception because the `nTasks` variable is boxed before the call to the method in each task. In other words, each method call is passed a separate variable that is independent of the others. `nTasks` is boxed again in the call to the method. Once again, this creates ten new boxed variables, which are independent of each other, `nTasks`, and the ten boxed variables created in the call to the method. The exception is thrown, then, because our code is attempting to release a lock on a newly created variable that was not previously locked. -Although you can box a value type variable before calling and , as shown in the following example, and pass the same boxed object to both methods, there is no advantage to doing this. Changes to the unboxed variable are not reflected in the boxed copy, and there is no way to change the value of the boxed copy. +Although you can box a value type variable before calling and , as shown in the following example, and pass the same boxed object to both methods, there is no advantage to doing this. Changes to the unboxed variable are not reflected in the boxed copy, and there is no way to change the value of the boxed copy. :::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/badbox1.cs" id="Snippet3"::: :::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/badbox1.vb" id="Snippet3"::: @@ -62,34 +62,34 @@ Note that you can synchronize on an object in multiple application domains if th ## The critical section -Use the and methods to mark the beginning and end of a critical section. +Use the and methods to mark the beginning and end of a critical section. > [!NOTE] -> The functionality provided by the and methods is identical to that provided by the [lock](/dotnet/csharp/language-reference/keywords/lock-statement) statement in C# and the [SyncLock](../../visual-basic/language-reference/statements/synclock-statement.md) statement in Visual Basic, except that the language constructs wrap the method overload and the method in a `try`…`finally` block to ensure that the monitor is released. +> The functionality provided by the and methods is identical to that provided by the [lock](/dotnet/csharp/language-reference/keywords/lock-statement) statement in C# and the [SyncLock](../../visual-basic/language-reference/statements/synclock-statement.md) statement in Visual Basic, except that the language constructs wrap the method overload and the method in a `try`…`finally` block to ensure that the monitor is released. -If the critical section is a set of contiguous instructions, then the lock acquired by the method guarantees that only a single thread can execute the enclosed code with the locked object. In this case, we recommend that you place that code in a `try` block and place the call to the method in a `finally` block. This ensures that the lock is released even if an exception occurs. The following code fragment illustrates this pattern. +If the critical section is a set of contiguous instructions, then the lock acquired by the method guarantees that only a single thread can execute the enclosed code with the locked object. In this case, we recommend that you place that code in a `try` block and place the call to the method in a `finally` block. This ensures that the lock is released even if an exception occurs. The following code fragment illustrates this pattern. :::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/Pattern2.cs" id="Snippet2"::: :::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/Pattern2.vb" id="Snippet2"::: This facility is typically used to synchronize access to a static or instance method of a class. -If a critical section spans an entire method, the locking facility can be achieved by placing the on the method, and specifying the value in the constructor of . When you use this attribute, the and method calls are not needed. The following code fragment illustrates this pattern: +If a critical section spans an entire method, the locking facility can be achieved by placing the on the method, and specifying the value in the constructor of . When you use this attribute, the and method calls are not needed. The following code fragment illustrates this pattern: :::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/Pattern2.cs" id="Snippet3"::: :::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/Pattern2.vb" id="Snippet3"::: Note that the attribute causes the current thread to hold the lock until the method returns; if the lock can be released sooner, use the class, the C# [lock](/dotnet/csharp/language-reference/keywords/lock-statement) statement, or the Visual Basic [SyncLock](../../visual-basic/language-reference/statements/synclock-statement.md) statement inside of the method instead of the attribute. -While it is possible for the and statements that lock and release a given object to cross member or class boundaries or both, this practice is not recommended. +While it is possible for the and statements that lock and release a given object to cross member or class boundaries or both, this practice is not recommended. ## Pulse, PulseAll, and Wait -Once a thread owns the lock and has entered the critical section that the lock protects, it can call the , , and methods. +Once a thread owns the lock and has entered the critical section that the lock protects, it can call the , , and methods. -When the thread that holds the lock calls , the lock is released and the thread is added to the waiting queue of the synchronized object. The first thread in the ready queue, if any, acquires the lock and enters the critical section. The thread that called is moved from the waiting queue to the ready queue when either the or the method is called by the thread that holds the lock (to be moved, the thread must be at the head of the waiting queue). The method returns when the calling thread reacquires the lock. +When the thread that holds the lock calls , the lock is released and the thread is added to the waiting queue of the synchronized object. The first thread in the ready queue, if any, acquires the lock and enters the critical section. The thread that called is moved from the waiting queue to the ready queue when either the or the method is called by the thread that holds the lock (to be moved, the thread must be at the head of the waiting queue). The method returns when the calling thread reacquires the lock. -When the thread that holds the lock calls , the thread at the head of the waiting queue is moved to the ready queue. The call to the method moves all the threads from the waiting queue to the ready queue. +When the thread that holds the lock calls , the thread at the head of the waiting queue is moved to the ready queue. The call to the method moves all the threads from the waiting queue to the ready queue. ## Monitors and wait handles @@ -105,17 +105,17 @@ The following example uses the class to synchron :::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/example1.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/example1.vb" id="Snippet1"::: -Because they can be accessed from any task running on a thread pool thread, access to the variables `total` and `n` must also be synchronized. The method is used for this purpose. +Because they can be accessed from any task running on a thread pool thread, access to the variables `total` and `n` must also be synchronized. The method is used for this purpose. -The following example demonstrates the combined use of the class (implemented with the `lock` or `SyncLock` language construct), the class, and the class. It defines two `internal` (in C#) or `Friend` (in Visual Basic) classes, `SyncResource` and `UnSyncResource`, that respectively provide synchronized and unsynchronized access to a resource. To ensure that the example illustrates the difference between the synchronized and unsynchronized access (which could be the case if each method call completes rapidly), the method includes a random delay: for threads whose property is even, the method calls to introduce a delay of 2,000 milliseconds. Note that, because the `SyncResource` class is not public, none of the client code takes a lock on the synchronized resource; the internal class itself takes the lock. This prevents malicious code from taking a lock on a public object. +The following example demonstrates the combined use of the class (implemented with the `lock` or `SyncLock` language construct), the class, and the class. It defines two `internal` (in C#) or `Friend` (in Visual Basic) classes, `SyncResource` and `UnSyncResource`, that respectively provide synchronized and unsynchronized access to a resource. To ensure that the example illustrates the difference between the synchronized and unsynchronized access (which could be the case if each method call completes rapidly), the method includes a random delay: for threads whose property is even, the method calls to introduce a delay of 2,000 milliseconds. Note that, because the `SyncResource` class is not public, none of the client code takes a lock on the synchronized resource; the internal class itself takes the lock. This prevents malicious code from taking a lock on a public object. :::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/source.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/source.vb" id="Snippet1"::: -The example defines a variable, `numOps`, that defines the number of threads that will attempt to access the resource. The application thread calls the method for synchronized and unsynchronized access five times each. The method has a single parameter, a delegate that accepts no parameters and returns no value. For synchronized access, it invokes the `SyncUpdateResource` method; for unsynchronized access, it invokes the `UnSyncUpdateResource` method. After each set of method calls, the application thread calls the [AutoResetEvent.WaitOne](xref:System.Threading.WaitHandle.WaitOne%2A) method so that it blocks until the instance is signaled. +The example defines a variable, `numOps`, that defines the number of threads that will attempt to access the resource. The application thread calls the method for synchronized and unsynchronized access five times each. The method has a single parameter, a delegate that accepts no parameters and returns no value. For synchronized access, it invokes the `SyncUpdateResource` method; for unsynchronized access, it invokes the `UnSyncUpdateResource` method. After each set of method calls, the application thread calls the [AutoResetEvent.WaitOne](xref:System.Threading.WaitHandle.WaitOne*) method so that it blocks until the instance is signaled. -Each call to the `SyncUpdateResource` method calls the internal `SyncResource.Access` method and then calls the method to decrement the `numOps` counter. The method Is used to decrement the counter, because otherwise you cannot be certain that a second thread will access the value before a first thread's decremented value has been stored in the variable. When the last synchronized worker thread decrements the counter to zero, indicating that all synchronized threads have completed accessing the resource, the `SyncUpdateResource` method calls the method, which signals the main thread to continue execution. +Each call to the `SyncUpdateResource` method calls the internal `SyncResource.Access` method and then calls the method to decrement the `numOps` counter. The method Is used to decrement the counter, because otherwise you cannot be certain that a second thread will access the value before a first thread's decremented value has been stored in the variable. When the last synchronized worker thread decrements the counter to zero, indicating that all synchronized threads have completed accessing the resource, the `SyncUpdateResource` method calls the method, which signals the main thread to continue execution. -Each call to the `UnSyncUpdateResource` method calls the internal `UnSyncResource.Access` method and then calls the method to decrement the `numOps` counter. Once again, the method Is used to decrement the counter to ensure that a second thread does not access the value before a first thread's decremented value has been assigned to the variable. When the last unsynchronized worker thread decrements the counter to zero, indicating that no more unsynchronized threads need to access the resource, the `UnSyncUpdateResource` method calls the method, which signals the main thread to continue execution. +Each call to the `UnSyncUpdateResource` method calls the internal `UnSyncResource.Access` method and then calls the method to decrement the `numOps` counter. Once again, the method Is used to decrement the counter to ensure that a second thread does not access the value before a first thread's decremented value has been assigned to the variable. When the last unsynchronized worker thread decrements the counter to zero, indicating that no more unsynchronized threads need to access the resource, the `UnSyncUpdateResource` method calls the method, which signals the main thread to continue execution. As the output from the example shows, synchronized access ensures that the calling thread exits the protected resource before another thread can access it; each thread waits on its predecessor. On the other hand, without the lock, the `UnSyncResource.Access` method is called in the order in which threads reach it. diff --git a/docs/fundamentals/runtime-libraries/system-threading-readerwriterlockslim.md b/docs/fundamentals/runtime-libraries/system-threading-readerwriterlockslim.md index 9777fb1b34bb4..96a005f88deff 100644 --- a/docs/fundamentals/runtime-libraries/system-threading-readerwriterlockslim.md +++ b/docs/fundamentals/runtime-libraries/system-threading-readerwriterlockslim.md @@ -15,7 +15,7 @@ Use to protect a resource that is r > [!NOTE] > > - is similar to , but it has simplified rules for recursion and for upgrading and downgrading lock state. avoids many cases of potential deadlock. In addition, the performance of is significantly better than . is recommended for all new development. -> - is not thread-abort safe. You should not use it in an environment where threads accessing it can be aborted, such as .NET Framework. If you're using .NET Core or .NET 5+, it should be fine. is not supported in .NET Core and [is obsolete](../../core/compatibility/core-libraries/5.0/thread-abort-obsolete.md) in .NET 5 and later versions. +> - is not thread-abort safe. You should not use it in an environment where threads accessing it can be aborted, such as .NET Framework. If you're using .NET Core or .NET 5+, it should be fine. is not supported in .NET Core and [is obsolete](../../core/compatibility/core-libraries/5.0/thread-abort-obsolete.md) in .NET 5 and later versions. By default, new instances of are created with the flag and do not allow recursion. This default policy is recommended for all new development, because recursion introduces unnecessary complications and makes your code more prone to deadlocks. To simplify migration from existing projects that use or , you can use the flag to create instances of that allow recursion. @@ -24,7 +24,7 @@ A thread can enter the lock in three modes: read mode, write mode, and upgradeab Regardless of recursion policy, only one thread can be in write mode at any time. When a thread is in write mode, no other thread can enter the lock in any mode. Only one thread can be in upgradeable mode at any time. Any number of threads can be in read mode, and there can be one thread in upgradeable mode while other threads are in read mode. > [!IMPORTANT] -> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. +> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. has managed thread affinity; that is, each object must make its own method calls to enter and exit lock modes. No thread can change the mode of another thread. @@ -41,7 +41,7 @@ If a does not allow recursion, a th ## Upgrade and downgrade locks -Upgradeable mode is intended for cases where a thread usually reads from the protected resource, but might need to write to it if some condition is met. A thread that has entered a in upgradeable mode has read access to the protected resource, and can upgrade to write mode by calling the or methods. Because there can be only one thread in upgradeable mode at a time, upgrading to write mode cannot deadlock when recursion is not allowed, which is the default policy. +Upgradeable mode is intended for cases where a thread usually reads from the protected resource, but might need to write to it if some condition is met. A thread that has entered a in upgradeable mode has read access to the protected resource, and can upgrade to write mode by calling the or methods. Because there can be only one thread in upgradeable mode at a time, upgrading to write mode cannot deadlock when recursion is not allowed, which is the default policy. > [!IMPORTANT] > Regardless of recursion policy, a thread that initially entered read mode is not allowed to upgrade to upgradeable mode or write mode, because that pattern creates a strong probability of deadlocks. For example, if two threads in read mode both try to enter write mode, they will deadlock. Upgradeable mode is designed to avoid such deadlocks. @@ -53,13 +53,13 @@ When the thread in upgradeable mode exits write mode, other threads that are wai > [!IMPORTANT] > If you allow multiple threads to enter write mode or upgradeable mode, you must not allow one thread to monopolize upgradeable mode. Otherwise, threads that try to enter write mode directly will be blocked indefinitely, and while they are blocked, other threads will be unable to enter read mode. -A thread in upgradeable mode can downgrade to read mode by first calling the method and then calling the method. This downgrade pattern is allowed for all lock recursion policies, even . +A thread in upgradeable mode can downgrade to read mode by first calling the method and then calling the method. This downgrade pattern is allowed for all lock recursion policies, even . After downgrading to read mode, a thread cannot reenter upgradeable mode until it has exited from read mode. ## Enter the lock recursively -You can create a that supports recursive lock entry by using the constructor that specifies lock policy, and specifying . +You can create a that supports recursive lock entry by using the constructor that specifies lock policy, and specifying . > [!NOTE] > The use of recursion is not recommended for new development, because it introduces unnecessary complications and makes your code more prone to deadlocks. @@ -85,7 +85,7 @@ You may find it useful to think of the lock in terms of its states. A [!NOTE] - > A thread can enter the lock in read mode by using the or methods, or by downgrading from upgradeable mode. + > A thread can enter the lock in read mode by using the or methods, or by downgrading from upgradeable mode. - Upgrade: In this state, one thread has entered the lock for read access with the option to upgrade to write access (that is, in upgradeable mode), and zero or more threads have entered the lock for read access. No more than one thread at a time can enter the lock with the option to upgrade; additional threads that try to enter upgradeable mode are blocked. @@ -114,7 +114,7 @@ The subsequent state of the lock is always Write (W) in the first two cases and ## Examples -The following example shows a simple synchronized cache that holds strings with integer keys. An instance of is used to synchronize access to the that serves as the inner cache. +The following example shows a simple synchronized cache that holds strings with integer keys. An instance of is used to synchronize access to the that serves as the inner cache. The example includes simple methods to add to the cache, delete from the cache, and read from the cache. To demonstrate time-outs, the example includes a method that adds to the cache only if it can do so within a specified time-out. @@ -129,7 +129,7 @@ The example uses the parameterless constructor to create the lock, so recursion :::code language="csharp" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/csharp/classexample1.cs" id="Snippet12"::: :::code language="vb" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/vb/classexample1.vb" id="Snippet12"::: -The following code then uses the `SynchronizedCache` object to store a dictionary of vegetable names. It creates three tasks. The first writes the names of vegetables stored in an array to a `SynchronizedCache` instance. The second and third task display the names of the vegetables, the first in ascending order (from low index to high index), the second in descending order. The final task searches for the string "cucumber" and, when it finds it, calls the method to substitute the string "green bean". +The following code then uses the `SynchronizedCache` object to store a dictionary of vegetable names. It creates three tasks. The first writes the names of vegetables stored in an array to a `SynchronizedCache` instance. The second and third task display the names of the vegetables, the first in ascending order (from low index to high index), the second in descending order. The final task searches for the string "cucumber" and, when it finds it, calls the method to substitute the string "green bean". :::code language="csharp" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/csharp/classexample1.cs" id="Snippet11"::: :::code language="vb" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/vb/classexample1.vb" id="Snippet11"::: diff --git a/docs/fundamentals/runtime-libraries/system-threading-tasks-task.md b/docs/fundamentals/runtime-libraries/system-threading-tasks-task.md index e97c0c9ad25d0..dabd78b29b965 100644 --- a/docs/fundamentals/runtime-libraries/system-threading-tasks-task.md +++ b/docs/fundamentals/runtime-libraries/system-threading-tasks-task.md @@ -11,19 +11,19 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The class represents a single operation that does not return a value and that usually executes asynchronously. objects are one of the central components of the [task-based asynchronous pattern](../../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md) first introduced in .NET Framework 4. Because the work performed by a object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the property, as well as the , , and properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform. +The class represents a single operation that does not return a value and that usually executes asynchronously. objects are one of the central components of the [task-based asynchronous pattern](../../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md) first introduced in .NET Framework 4. Because the work performed by a object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the property, as well as the , , and properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform. -For operations that return values, you use the class. +For operations that return values, you use the class. ## Task instantiation -The following example creates and executes four tasks. Three tasks execute an delegate named `action`, which accepts an argument of type . A fourth task executes a lambda expression (an delegate) that is defined inline in the call to the task creation method. Each task is instantiated and run in a different way: +The following example creates and executes four tasks. Three tasks execute an delegate named `action`, which accepts an argument of type . A fourth task executes a lambda expression (an delegate) that is defined inline in the call to the task creation method. Each task is instantiated and run in a different way: - Task `t1` is instantiated by calling a Task class constructor, but is started by calling its method only after task `t2` has started. -- Task `t2` is instantiated and started in a single method call by calling the method. +- Task `t2` is instantiated and started in a single method call by calling the method. -- Task `t3` is instantiated and started in a single method call by calling the method. +- Task `t3` is instantiated and started in a single method call by calling the method. - Task `t4` is executed synchronously on the main thread by calling the method. @@ -35,13 +35,13 @@ Because task `t4` executes synchronously, it executes on the main application th ## Create and execute a task -You can create instances in a variety of ways. The most common approach is to call the static method. The method provides a simple way to start a task using default values and without requiring additional parameters. The following example uses the method to start a task that loops and then displays the number of loop iterations: +You can create instances in a variety of ways. The most common approach is to call the static method. The method provides a simple way to start a task using default values and without requiring additional parameters. The following example uses the method to start a task that loops and then displays the number of loop iterations: :::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/run1.cs" id="Snippet6"::: :::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/run1.fs" id="Snippet6"::: :::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/run1.vb" id="Snippet6"::: -An alternative is the static method. The property returns a object. Overloads of the method let you specify parameters to pass to the task creation options and a task scheduler. The following example uses the method to start a task. It is functionally equivalent to the code in the previous example. +An alternative is the static method. The property returns a object. Overloads of the method let you specify parameters to pass to the task creation options and a task scheduler. The following example uses the method to start a task. It is functionally equivalent to the code in the previous example. :::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/startnew1.cs" id="Snippet7"::: :::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/startnew1.fs" id="Snippet7"::: @@ -51,41 +51,41 @@ For more complete examples, see [Task-based Asynchronous Programming](../../stan ## Separate task creation and execution -The class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the or method is the preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation and scheduling must be separated, you can use the constructors and then call the method to schedule the task for execution at a later time. +The class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the or method is the preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation and scheduling must be separated, you can use the constructors and then call the method to schedule the task for execution at a later time. ## Wait for a task to complete Because tasks typically run asynchronously on a thread pool thread, the thread that creates and starts the task continues execution as soon as the task has been instantiated. In some cases, when the calling thread is the main application thread, the app may terminate before the task actually begins execution. In others, your application's logic may require that the calling thread continue execution only when one or more tasks have completed execution. You can synchronize the execution of the calling thread and the asynchronous tasks it launches by calling a `Wait` method to wait for one or more tasks to complete. -To wait for a single task to complete, you can call its method. A call to the method blocks the calling thread until the single class instance has completed execution. +To wait for a single task to complete, you can call its method. A call to the method blocks the calling thread until the single class instance has completed execution. -The following example calls the parameterless method to wait unconditionally until a task completes. The task simulates work by calling the method to sleep for two seconds. +The following example calls the parameterless method to wait unconditionally until a task completes. The task simulates work by calling the method to sleep for two seconds. :::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/Wait1.cs" id="Snippet8"::: :::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/Wait1.fs" id="Snippet8"::: :::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/Wait1.vb" id="Snippet8"::: -You can also conditionally wait for a task to complete. The and methods block the calling thread until the task finishes or a timeout interval elapses, whichever comes first. Since the following example launches a task that sleeps for two seconds but defines a one-second timeout value, the calling thread blocks until the timeout expires and before the task has completed execution. +You can also conditionally wait for a task to complete. The and methods block the calling thread until the task finishes or a timeout interval elapses, whichever comes first. Since the following example launches a task that sleeps for two seconds but defines a one-second timeout value, the calling thread blocks until the timeout expires and before the task has completed execution. :::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/Wait2.cs" id="Snippet9"::: :::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/Wait2.fs" id="Snippet9"::: :::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/Wait2.vb" id="Snippet9"::: -You can also supply a cancellation token by calling the and methods. If the token's property is `true` or becomes `true` while the method is executing, the method throws an . +You can also supply a cancellation token by calling the and methods. If the token's property is `true` or becomes `true` while the method is executing, the method throws an . -In some cases, you may want to wait for the first of a series of executing tasks to complete, but don't care which task it is. For this purpose, you can call one of the overloads of the method. The following example creates three tasks, each of which sleeps for an interval determined by a random number generator. The method waits for the first task to complete. The example then displays information about the status of all three tasks. +In some cases, you may want to wait for the first of a series of executing tasks to complete, but don't care which task it is. For this purpose, you can call one of the overloads of the method. The following example creates three tasks, each of which sleeps for an interval determined by a random number generator. The method waits for the first task to complete. The example then displays information about the status of all three tasks. :::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/WhenAny1.cs" id="Snippet10"::: :::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/WhenAny1.fs" id="Snippet10"::: :::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/WaitAny1.vb" id="Snippet10"::: -You can also wait for all of a series of tasks to complete by calling the method. The following example creates ten tasks, waits for all ten to complete, and then displays their status. +You can also wait for all of a series of tasks to complete by calling the method. The following example creates ten tasks, waits for all ten to complete, and then displays their status. :::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll1.cs" id="Snippet11"::: :::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/WaitAll1.fs" id="Snippet11"::: :::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/WaitAll1.vb" id="Snippet11"::: -Note that when you wait for one or more tasks to complete, any exceptions thrown in the running tasks are propagated on the thread that calls the `Wait` method, as the following example shows. It launches 12 tasks, three of which complete normally and three of which throw an exception. Of the remaining six tasks, three are cancelled before they start, and three are cancelled while they are executing. Exceptions are thrown in the method call and are handled by a `try`/`catch` block. +Note that when you wait for one or more tasks to complete, any exceptions thrown in the running tasks are propagated on the thread that calls the `Wait` method, as the following example shows. It launches 12 tasks, three of which complete normally and three of which throw an exception. Of the remaining six tasks, three are cancelled before they start, and three are cancelled while they are executing. Exceptions are thrown in the method call and are handled by a `try`/`catch` block. :::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll2.cs" id="Snippet12"::: :::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/WaitAll2.fs" id="Snippet12"::: diff --git a/docs/fundamentals/runtime-libraries/system-threading-tasks-taskscheduler.md b/docs/fundamentals/runtime-libraries/system-threading-tasks-taskscheduler.md index a802d0663ddc9..8eb7d70b8678f 100644 --- a/docs/fundamentals/runtime-libraries/system-threading-tasks-taskscheduler.md +++ b/docs/fundamentals/runtime-libraries/system-threading-tasks-taskscheduler.md @@ -22,7 +22,7 @@ The default scheduler for the Task Parallel Library and PLINQ uses the .NET thre ### The global queue vs. local queues -The thread pool maintains a global FIFO (first-in, first-out) work queue for threads in each application domain. Whenever a program calls the (or ) method, the work is put on this shared queue and eventually de-queued onto the next thread that becomes available. Starting with .NET Framework 4, this queue uses a lock-free algorithm that resembles the class. By using this lock-free implementation, the thread pool spends less time when it queues and de-queues work items. This performance benefit is available to all programs that use the thread pool. +The thread pool maintains a global FIFO (first-in, first-out) work queue for threads in each application domain. Whenever a program calls the (or ) method, the work is put on this shared queue and eventually de-queued onto the next thread that becomes available. Starting with .NET Framework 4, this queue uses a lock-free algorithm that resembles the class. By using this lock-free implementation, the thread pool spends less time when it queues and de-queues work items. This performance benefit is available to all programs that use the thread pool. Top-level tasks, which are tasks that are not created in the context of another task, are put on the global queue just like any other work item. However, nested or child tasks, which are created in the context of another task, are handled quite differently. A child or nested task is put on a local queue that is specific to the thread on which the parent task is executing. The parent task may be a top-level task or it also may be the child of another task. When this thread is ready for more work, it first looks in the local queue. If work items are waiting there, they can be accessed quickly. The local queues are accessed in last-in, first-out order (LIFO) to preserve cache locality and reduce contention. For more information about child tasks and nested tasks, see [Attached and Detached Child Tasks](../../standard/parallel-programming/attached-and-detached-child-tasks.md). @@ -42,9 +42,9 @@ In some cases when a is waited on, it may be ## Specify a synchronization context -You can use the method to specify that a task should be scheduled to run on a particular thread. This is useful in frameworks such as Windows Forms and Windows Presentation Foundation where access to user interface objects is often restricted to code that is running on the same thread on which the UI object was created. +You can use the method to specify that a task should be scheduled to run on a particular thread. This is useful in frameworks such as Windows Forms and Windows Presentation Foundation where access to user interface objects is often restricted to code that is running on the same thread on which the UI object was created. -The following example uses the method in a Windows Presentation Foundation (WPF) app to schedule a task on the same thread that the user interface (UI) control was created on. The example creates a mosaic of images that are randomly selected from a specified directory. The WPF objects are used to load and resize the images. The raw pixels are then passed to a task that uses a loop to write the pixel data into a large single-byte array. No synchronization is required because no two tiles occupy the same array elements. The tiles can also be written in any order because their position is calculated independently of any other tile. The large array is then passed to a task that runs on the UI thread, where the pixel data is loaded into an Image control. +The following example uses the method in a Windows Presentation Foundation (WPF) app to schedule a task on the same thread that the user interface (UI) control was created on. The example creates a mosaic of images that are randomly selected from a specified directory. The WPF objects are used to load and resize the images. The raw pixels are then passed to a task that uses a loop to write the pixel data into a large single-byte array. No synchronization is required because no two tiles occupy the same array elements. The tiles can also be written in any order because their position is calculated independently of any other tile. The large array is then passed to a task that runs on the UI thread, where the pixel data is loaded into an Image control. The example moves data off the UI thread, modifies it by using parallel loops and objects, and then passes it back to a task that runs on the UI thread. This approach is useful when you have to use the Task Parallel Library to perform operations that either are not supported by the WPF API, or are not sufficiently fast. Another way to create an image mosaic in WPF is to use a control and add images to it. The handles the work of positioning the tiles. However, this work can only be performed on the UI thread. diff --git a/docs/fundamentals/runtime-libraries/system-threading-thread.md b/docs/fundamentals/runtime-libraries/system-threading-thread.md index ea4362c976b6b..274d1afb4a624 100644 --- a/docs/fundamentals/runtime-libraries/system-threading-thread.md +++ b/docs/fundamentals/runtime-libraries/system-threading-thread.md @@ -17,7 +17,7 @@ When a process starts, the common language runtime automatically creates a singl ## Start a thread -You start a thread by supplying a delegate that represents the method the thread is to execute in its class constructor. You then call the method to begin execution. +You start a thread by supplying a delegate that represents the method the thread is to execute in its class constructor. You then call the method to begin execution. The constructors can take either of two delegate types, depending on whether you can pass an argument to the method to be executed: @@ -49,7 +49,7 @@ The constructors can take either of two delegate The method executed by the delegate can then cast (in C#) or convert (in Visual Basic) the parameter to the appropriate type. - The following example is identical to the previous one, except that it calls the constructor. This version of the `ExecuteInForeground` method has a single parameter that represents the approximate number of milliseconds the loop is to execute. + The following example is identical to the previous one, except that it calls the constructor. This version of the `ExecuteInForeground` method has a single parameter that represents the approximate number of milliseconds the loop is to execute. :::code language="csharp" source="./snippets/System.Threading/Thread/Overview/csharp/ThreadStart2.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System.Threading/Thread/Overview/fsharp/ThreadStart2.fs" id="Snippet2"::: @@ -80,7 +80,7 @@ The following threads execute in the background by default: - Thread pool threads, which come from a pool of worker threads maintained by the runtime. You can configure the thread pool and schedule work on thread pool threads by using the class. > [!NOTE] - > Task-based asynchronous operations automatically execute on thread pool threads. Task-based asynchronous operations use the and classes to implement the [task-based asynchronous pattern](../../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md). + > Task-based asynchronous operations automatically execute on thread pool threads. Task-based asynchronous operations use the and classes to implement the [task-based asynchronous pattern](../../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md). - All threads that enter the managed execution environment from unmanaged code. @@ -100,16 +100,16 @@ Each thread has a culture, represented by the The and properties don't work reliably when used with any thread other than the current thread. In .NET Framework, reading these properties is reliable, although setting these properties for a thread other than the current thread is not. On .NET Core, an is thrown if a thread attempts to read or write these properties on a different thread. > We recommend that you use the and properties to retrieve and set the current culture. -When a new thread is instantiated, its culture and UI culture are defined by the current system culture and UI culture, and not by the culture and UI culture of the thread from which the new thread is created. This means, for example, that if the current system culture is English (United States) and the current culture of the primary application thread is French (France), the culture of a new thread created by calling the constructor from the primary thread is English (United States), and not French (France). For more information, see the "Culture and threads" section of the class topic. +When a new thread is instantiated, its culture and UI culture are defined by the current system culture and UI culture, and not by the culture and UI culture of the thread from which the new thread is created. This means, for example, that if the current system culture is English (United States) and the current culture of the primary application thread is French (France), the culture of a new thread created by calling the constructor from the primary thread is English (United States), and not French (France). For more information, see the "Culture and threads" section of the class topic. > [!IMPORTANT] > This is not true of threads that execute asynchronous operations for apps that target .NET Framework 4.6 and later versions. In this case, the culture and UI culture is part of an asynchronous operation's context; the thread on which an asynchronous operation executes by default inherits the culture and UI culture of the thread from which the asynchronous operation was launched. For more information, see the "Culture and task-based asynchronous operations" section of the class remarks. You can do either of the following to ensure that all of the threads executing in an application share the same culture and UI culture: -- You can pass a object that represents that culture to the delegate or the method. +- You can pass a object that represents that culture to the delegate or the method. -- For apps running on .NET Framework 4.5 and later versions, you can define the culture and UI culture that is to be assigned to all threads created in an application domain by setting the value of the and properties. Note that this is a per-application domain setting. +- For apps running on .NET Framework 4.5 and later versions, you can define the culture and UI culture that is to be assigned to all threads created in an application domain by setting the value of the and properties. Note that this is a per-application domain setting. For more information and examples, see the "Culture and threads" section of the class remarks. @@ -119,7 +119,7 @@ You can retrieve a number of property values that provide information about a th - A name. is a write-once property that you can use to identify a thread. Its default value is `null`. -- A hash code, which you can retrieve by calling the method. The hash code can be used to uniquely identify a thread; for the lifetime of your thread, its hash code will not collide with the value from any other thread, regardless of the application domain from which you obtain the value. +- A hash code, which you can retrieve by calling the method. The hash code can be used to uniquely identify a thread; for the lifetime of your thread, its hash code will not collide with the value from any other thread, regardless of the application domain from which you obtain the value. - A thread ID. The value of the read-only property is assigned by the runtime and uniquely identifies a thread within its process. diff --git a/docs/fundamentals/runtime-libraries/system-timespan-parse.md b/docs/fundamentals/runtime-libraries/system-timespan-parse.md index bdfce02e7c534..a126aa7b5c7b9 100644 --- a/docs/fundamentals/runtime-libraries/system-timespan-parse.md +++ b/docs/fundamentals/runtime-libraries/system-timespan-parse.md @@ -11,7 +11,7 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The input string to the methods contains a time interval specification in the form: +The input string to the methods contains a time interval specification in the form: `[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]` @@ -30,7 +30,7 @@ Elements in square brackets (`[` and `]`) are optional. One selection from the l | *.* | A culture-sensitive symbol that separates seconds from fractions of a second. The invariant format uses a period (".") character. | | *ff* | Optional fractional seconds, consisting of one to seven decimal digits. | -If the input string is not a day value only, it must include an hours and a minutes component; other components are optional. If they are present, the values of each time component must fall within a specified range. For example, the value of *hh*, the hours component, must be between 0 and 23. Because of this, passing "23:00:00" to the method returns a time interval of 23 hours. On the other hand, passing "24:00:00" returns a time interval of 24 days. Because "24" is outside the range of the hours component, it is interpreted as the days component. +If the input string is not a day value only, it must include an hours and a minutes component; other components are optional. If they are present, the values of each time component must fall within a specified range. For example, the value of *hh*, the hours component, must be between 0 and 23. Because of this, passing "23:00:00" to the method returns a time interval of 23 hours. On the other hand, passing "24:00:00" returns a time interval of 24 days. Because "24" is outside the range of the hours component, it is interpreted as the days component. The components of the input string must collectively specify a time interval that is greater than or equal to and less than or equal to . diff --git a/docs/fundamentals/runtime-libraries/system-timespan-tryparse.md b/docs/fundamentals/runtime-libraries/system-timespan-tryparse.md index 1e72168a1ced2..d7d8e251e523c 100644 --- a/docs/fundamentals/runtime-libraries/system-timespan-tryparse.md +++ b/docs/fundamentals/runtime-libraries/system-timespan-tryparse.md @@ -67,9 +67,9 @@ The implementation that provides culture-specific information about the format of the returned string. The `formatProvider` parameter can be any of the following: -- A object that represents the culture whose formatting conventions are to be reflected in the returned string. The object returned by the property defines the formatting of the returned string. +- A object that represents the culture whose formatting conventions are to be reflected in the returned string. The object returned by the property defines the formatting of the returned string. - A object that defines the formatting of the returned string. -- A custom object that implements the interface. Its method returns a object that provides formatting information. +- A custom object that implements the interface. Its method returns a object that provides formatting information. If `formatProvider` is `null`, the object that is associated with the current culture is used. diff --git a/docs/fundamentals/runtime-libraries/system-timespan.md b/docs/fundamentals/runtime-libraries/system-timespan.md index 85a6559d68f0a..0d5fbd199f93f 100644 --- a/docs/fundamentals/runtime-libraries/system-timespan.md +++ b/docs/fundamentals/runtime-libraries/system-timespan.md @@ -50,17 +50,17 @@ You can instantiate a value in a number of ways: values are returned by arithmetic operators and methods of the , , and structures. -- By parsing the string representation of a value. You can use the and methods to convert strings that contain time intervals to values. The following example uses the method to convert an array of strings to values. +- By parsing the string representation of a value. You can use the and methods to convert strings that contain time intervals to values. The following example uses the method to convert an array of strings to values. :::code language="csharp" source="./snippets/System/TimeSpan/Overview/csharp/instantiate1.cs" id="Snippet5"::: :::code language="fsharp" source="./snippets/System/TimeSpan/Overview/fsharp/instantiate1.fs" id="Snippet5"::: :::code language="vb" source="./snippets/System/TimeSpan/Overview/vb/instantiate1.vb" id="Snippet5"::: - In addition, you can define the precise format of the input string to be parsed and converted to a value by calling the or method. + In addition, you can define the precise format of the input string to be parsed and converted to a value by calling the or method. ## Perform operations on TimeSpan values -You can add and subtract time durations either by using the and operators, or by calling the and methods. You can also compare two time durations by calling the , , and methods. The structure also includes the and methods, which convert time intervals to positive and negative values, +You can add and subtract time durations either by using the and operators, or by calling the and methods. You can also compare two time durations by calling the , , and methods. The structure also includes the and methods, which convert time intervals to positive and negative values, The range of values is to . @@ -68,7 +68,7 @@ The range of values is to A value can be represented as [*-*]*d*.*hh*:*mm*:*ss*.*ff*, where the optional minus sign indicates a negative time interval, the *d* component is days, *hh* is hours as measured on a 24-hour clock, *mm* is minutes, *ss* is seconds, and *ff* is fractions of a second. That is, a time interval consists of a positive or negative number of days without a time of day, or a number of days with a time of day, or only a time of day. -Beginning with .NET Framework 4, the structure supports culture-sensitive formatting through the overloads of its method, which converts a value to its string representation. The default method returns a time interval by using an invariant format that is identical to its return value in previous versions of .NET Framework. The overload lets you specify a format string that defines the string representation of the time interval. The overload lets you specify a format string and the culture whose formatting conventions are used to create the string representation of the time interval. supports both standard and custom format strings. (For more information, see [Standard TimeSpan Format Strings](../../standard/base-types/standard-timespan-format-strings.md) and [Custom TimeSpan Format Strings](../../standard/base-types/custom-timespan-format-strings.md).) However, only standard format strings are culture-sensitive. +Beginning with .NET Framework 4, the structure supports culture-sensitive formatting through the overloads of its method, which converts a value to its string representation. The default method returns a time interval by using an invariant format that is identical to its return value in previous versions of .NET Framework. The overload lets you specify a format string that defines the string representation of the time interval. The overload lets you specify a format string and the culture whose formatting conventions are used to create the string representation of the time interval. supports both standard and custom format strings. (For more information, see [Standard TimeSpan Format Strings](../../standard/base-types/standard-timespan-format-strings.md) and [Custom TimeSpan Format Strings](../../standard/base-types/custom-timespan-format-strings.md).) However, only standard format strings are culture-sensitive. ## Restore legacy TimeSpan formatting diff --git a/docs/fundamentals/runtime-libraries/system-type-getproperty.md b/docs/fundamentals/runtime-libraries/system-type-getproperty.md index 878e7910babde..3cd4f84d88622 100644 --- a/docs/fundamentals/runtime-libraries/system-type-getproperty.md +++ b/docs/fundamentals/runtime-libraries/system-type-getproperty.md @@ -19,7 +19,7 @@ The search for `name` is case-sensitive. The search includes public static and p Situations in which occurs include the following: -- A type contains two indexed properties that have the same name but different numbers of parameters. To resolve the ambiguity, use an overload of the method that specifies parameter types. +- A type contains two indexed properties that have the same name but different numbers of parameters. To resolve the ambiguity, use an overload of the method that specifies parameter types. - A derived type declares a property that hides an inherited property with the same name, by using the `new` modifier (`Shadows` in Visual Basic). To resolve the ambiguity, use the method overload and add the flag to restrict the search to members that aren't inherited. ## method @@ -38,7 +38,7 @@ The following modifier flags can be used t Situations in which occurs include the following: -- A type contains two indexed properties that have the same name but different numbers of parameters. To resolve the ambiguity, use an overload of the method that specifies parameter types. +- A type contains two indexed properties that have the same name but different numbers of parameters. To resolve the ambiguity, use an overload of the method that specifies parameter types. - A derived type declares a property that hides an inherited property with the same name, using the `new` modifier (`Shadows` in Visual Basic). To resolve the ambiguity, include to restrict the search to members that are not inherited. ## [GetProperty(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Type, System.Type[], System.Reflection.ParameterModifier[])](xref:System.Type.GetProperty(System.String,System.Reflection.BindingFlags,System.Reflection.Binder,System.Type,System.Type[],System.Reflection.ParameterModifier[])) method @@ -78,6 +78,6 @@ The following modifier flags can be used t Visual Basic, C#, and C++ have simplified syntax for accessing indexed properties and allow one indexed property to be a default for its type. For example, if the variable `myList` refers to an , the syntax `myList[3]` (`myList(3)` in Visual Basic) retrieves the element with the index of 3. You can overload the property. -In C#, this feature is called an indexer and cannot be referred to by name. By default, a C# indexer appears in metadata as an indexed property named `Item`. However, a class library developer can use the attribute to change the name of the indexer in the metadata. For example, the class has an indexer named . Indexed properties created using languages other than C# can have names other than `Item`, as well. +In C#, this feature is called an indexer and cannot be referred to by name. By default, a C# indexer appears in metadata as an indexed property named `Item`. However, a class library developer can use the attribute to change the name of the indexer in the metadata. For example, the class has an indexer named . Indexed properties created using languages other than C# can have names other than `Item`, as well. To determine whether a type has a default property, use the method to test for the attribute. If the type has , the property returns the name of the default property. diff --git a/docs/fundamentals/runtime-libraries/system-type-gettype.md b/docs/fundamentals/runtime-libraries/system-type-gettype.md index 61a3db5da34f9..7f9ca74a3f2b4 100644 --- a/docs/fundamentals/runtime-libraries/system-type-gettype.md +++ b/docs/fundamentals/runtime-libraries/system-type-gettype.md @@ -10,16 +10,16 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -Use the method overload and its associated overloads ( and ) to replace the default implementation of the method with more flexible implementations. By providing your own methods that resolve type names and the names of the assemblies that contain them, you can do the following: +Use the method overload and its associated overloads ( and ) to replace the default implementation of the method with more flexible implementations. By providing your own methods that resolve type names and the names of the assemblies that contain them, you can do the following: - Control which version of an assembly a type is loaded from. - Provide another place to look for a type name that does not include an assembly name. - Load assemblies using partial assembly names. - Return subclasses of that are not created by the common language runtime (CLR). -For example, in version-tolerant serialization this method enables you to search for a "best fit" assembly by using a partial name. Other overloads of the method require an assembly-qualified type name, which includes the version number. +For example, in version-tolerant serialization this method enables you to search for a "best fit" assembly by using a partial name. Other overloads of the method require an assembly-qualified type name, which includes the version number. -Alternate implementations of the type system may need to return subclasses of that are not created by the CLR; all types that are returned by other overloads of the method are runtime types. +Alternate implementations of the type system may need to return subclasses of that are not created by the CLR; all types that are returned by other overloads of the method are runtime types. ## Usage notes @@ -47,11 +47,11 @@ General usage notes: The `assemblyResolver` method receives an object, which is produced by parsing the string assembly name that is included in `typeName`. If `typeName` does not contain an assembly name, `assemblyResolver` is not called and `null` is passed to `typeResolver`. -If `assemblyResolver` is not supplied, standard assembly probing is used to locate the assembly. If `assemblyResolver` is provided, the method does not do standard probing; in that case you must ensure that your `assemblyResolver` can handle all the assemblies you pass to it. +If `assemblyResolver` is not supplied, standard assembly probing is used to locate the assembly. If `assemblyResolver` is provided, the method does not do standard probing; in that case you must ensure that your `assemblyResolver` can handle all the assemblies you pass to it. The `assemblyResolver` method should return `null` if the assembly cannot be resolved. If `assemblyResolver` returns `null`, `typeResolver` is not called and no further processing occurs; additionally, if `throwOnError` is `true`, a is thrown. -If the that is passed to `assemblyResolver` is a partial name, one or more of its parts are `null`. For example, if it has no version, the property is `null`. If the property, the property, and the method all return `null`, then only the simple name of the assembly was supplied. The `assemblyResolver` method can use or ignore all parts of the assembly name. +If the that is passed to `assemblyResolver` is a partial name, one or more of its parts are `null`. For example, if it has no version, the property is `null`. If the property, the property, and the method all return `null`, then only the simple name of the assembly was supplied. The `assemblyResolver` method can use or ignore all parts of the assembly name. The effects of different assembly resolution options are displayed as a table in the [Mixed name resolution](#mixed-name-resolution) section, for simple and assembly-qualified type names. @@ -65,17 +65,17 @@ The `typeResolver` method receives three arguments: - The simple name of the type. In the case of a nested type, this is the outermost containing type. In the case of a generic type, this is the simple name of the generic type. - A Boolean value that's `true` if the case of type names is to be ignored. -The implementation determines the way these arguments are used. The `typeResolver` method should return `null` if it cannot resolve the type. If `typeResolver` returns `null` and `throwOnError` is `true`, this overload of throws a . +The implementation determines the way these arguments are used. The `typeResolver` method should return `null` if it cannot resolve the type. If `typeResolver` returns `null` and `throwOnError` is `true`, this overload of throws a . The effects of different type resolution options are displayed as a table in the [Mixed name resolution](#mixed-name-resolution) section, for simple and assembly-qualified type names. #### Resolve nested types -If `typeName` is a nested type, only the name of the outermost containing type is passed to `typeResolver`. When `typeResolver` returns this type, the method is called recursively until the innermost nested type has been resolved. +If `typeName` is a nested type, only the name of the outermost containing type is passed to `typeResolver`. When `typeResolver` returns this type, the method is called recursively until the innermost nested type has been resolved. #### Resolve generic types -The is called recursively to resolve generic types: First to resolve the generic type itself, and then to resolve its type arguments. If a type argument is generic, is called recursively to resolve its type arguments, and so on. +The is called recursively to resolve generic types: First to resolve the generic type itself, and then to resolve its type arguments. If a type argument is generic, is called recursively to resolve its type arguments, and so on. The combination of `assemblyResolver` and `typeResolver` that you provide must be capable of resolving all levels of this recursion. For example, suppose you supply an `assemblyResolver` that controls the loading of `MyAssembly`. Suppose you want to resolve the generic type `Dictionary` (`Dictionary(Of String, MyType)` in Visual Basic). You might pass the following generic type name: @@ -83,7 +83,7 @@ The combination of `assemblyResolver` and `typeResolver` that you provide must b "System.Collections.Generic.Dictionary`2[System.String,[MyNamespace.MyType, MyAssembly]]" ``` -Notice that `MyType` is the only assembly-qualified type argument. The names of the and classes are not assembly-qualified. Your `typeResolver` must be able to handle either an assembly or `null`, because it will receive `null` for and . It can handle that case by calling an overload of the method that takes a string, because both of the unqualified type names are in mscorlib.dll/System.Private.CoreLib.dll: +Notice that `MyType` is the only assembly-qualified type argument. The names of the and classes are not assembly-qualified. Your `typeResolver` must be able to handle either an assembly or `null`, because it will receive `null` for and . It can handle that case by calling an overload of the method that takes a string, because both of the unqualified type names are in mscorlib.dll/System.Private.CoreLib.dll: :::code language="csharp" source="./snippets/System/Type/GetType/csharp/source.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Type/GetType/fsharp/source.fs" id="Snippet1"::: @@ -103,7 +103,7 @@ Because this assembly is neither mscorlib.dll/System.Private.CoreLib.dll nor the #### Resolve type names with special characters -Certain characters have special meanings in assembly-qualified names. If a simple type name contains these characters, the characters cause parsing errors when the simple name is part of an assembly-qualified name. To avoid the parsing errors, you must escape the special characters with a backslash before you can pass the assembly-qualified name to the method. For example, if a type is named `Strange]Type`, the escape character must be added ahead of the square bracket as follows: `Strange\]Type`. +Certain characters have special meanings in assembly-qualified names. If a simple type name contains these characters, the characters cause parsing errors when the simple name is part of an assembly-qualified name. To avoid the parsing errors, you must escape the special characters with a backslash before you can pass the assembly-qualified name to the method. For example, if a type is named `Strange]Type`, the escape character must be added ahead of the square bracket as follows: `Strange\]Type`. > [!NOTE] > Names with such special characters cannot be created in Visual Basic or C#, but can be created by using common intermediate language (CIL) or by emitting dynamic assemblies. @@ -119,7 +119,7 @@ The following table shows the special characters for type names. |`+` (plus)|Delimiter for nested types.| |`\` (backslash)|Escape character.| -Properties such as return correctly escaped strings. You must pass correctly escaped strings to the method. In turn, the method passes correctly escaped names to `typeResolver` and to the default type resolution methods. If you need to compare a name to an unescaped name in `typeResolver`, you must remove the escape characters. +Properties such as return correctly escaped strings. You must pass correctly escaped strings to the method. In turn, the method passes correctly escaped names to `typeResolver` and to the default type resolution methods. If you need to compare a name to an unescaped name in `typeResolver`, you must remove the escape characters. ## Mixed name resolution diff --git a/docs/fundamentals/runtime-libraries/system-type-makegenerictype.md b/docs/fundamentals/runtime-libraries/system-type-makegenerictype.md index 46070208a5d9e..424ee71cf78e5 100644 --- a/docs/fundamentals/runtime-libraries/system-type-makegenerictype.md +++ b/docs/fundamentals/runtime-libraries/system-type-makegenerictype.md @@ -11,23 +11,23 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The method allows you to write code that assigns specific types to the type parameters of a generic type definition, thus creating a object that represents a particular constructed type. You can use this object to create runtime instances of the constructed type. +The method allows you to write code that assigns specific types to the type parameters of a generic type definition, thus creating a object that represents a particular constructed type. You can use this object to create runtime instances of the constructed type. -Types constructed with can be open, that is, some of their type arguments can be type parameters of enclosing generic methods or types. You might use such open constructed types when you emit dynamic assemblies. For example, consider the classes `Base` and `Derived` in the following code. +Types constructed with can be open, that is, some of their type arguments can be type parameters of enclosing generic methods or types. You might use such open constructed types when you emit dynamic assemblies. For example, consider the classes `Base` and `Derived` in the following code. :::code language="csharp" source="./snippets/System/Type/MakeGenericType/csharp/remarks.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Type/MakeGenericType/fsharp/remarks.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/Type/MakeGenericType/vb/remarks.vb" id="Snippet1"::: -To generate `Derived` in a dynamic assembly, it is necessary to construct its base type. To do this, call the method on a object representing the class `Base`, using the generic type arguments and the type parameter `V` from `Derived`. Because types and generic type parameters are both represented by objects, an array containing both can be passed to the method. +To generate `Derived` in a dynamic assembly, it is necessary to construct its base type. To do this, call the method on a object representing the class `Base`, using the generic type arguments and the type parameter `V` from `Derived`. Because types and generic type parameters are both represented by objects, an array containing both can be passed to the method. > [!NOTE] -> A constructed type such as `Base` is useful when emitting code, but you cannot call the method on this type because it is not a generic type definition. To create a closed constructed type that can be instantiated, first call the method to get a object representing the generic type definition and then call with the desired type arguments. +> A constructed type such as `Base` is useful when emitting code, but you cannot call the method on this type because it is not a generic type definition. To create a closed constructed type that can be instantiated, first call the method to get a object representing the generic type definition and then call with the desired type arguments. -The object returned by is the same as the obtained by calling the method of the resulting constructed type, or the method of any constructed type that was created from the same generic type definition using the same type arguments. +The object returned by is the same as the obtained by calling the method of the resulting constructed type, or the method of any constructed type that was created from the same generic type definition using the same type arguments. > [!NOTE] -> An array of generic types is not itself a generic type. You cannot call on an array type such as `C[]` (`Dim ac() As C(Of T)` in Visual Basic). To construct a closed generic type from `C[]`, call to obtain the generic type definition `C`; call on the generic type definition to create the constructed type; and finally call the method on the constructed type to create the array type. The same is true of pointer types and `ref` types (`ByRef` in Visual Basic). +> An array of generic types is not itself a generic type. You cannot call on an array type such as `C[]` (`Dim ac() As C(Of T)` in Visual Basic). To construct a closed generic type from `C[]`, call to obtain the generic type definition `C`; call on the generic type definition to create the constructed type; and finally call the method on the constructed type to create the array type. The same is true of pointer types and `ref` types (`ByRef` in Visual Basic). For a list of the invariant conditions for terms used in generic reflection, see the property remarks. @@ -42,7 +42,7 @@ The type parameter list of the nested class `Inner` has two type parameters, `T` If the parameter list of the enclosing type has more than one type parameter, all the type parameters in order are included in the type parameter list of the nested type. -To construct a generic type from the generic type definition for a nested type, call the method with the array formed by concatenating the type argument arrays of all the enclosing types, beginning with the outermost generic type, and ending with the type argument array of the nested type itself, if it has type parameters of its own. To create an instance of `Innermost1`, call the method with an array containing three types, to be assigned to T, U, and V. To create an instance of `Innermost2`, call the method with an array containing two types, to be assigned to T and U. +To construct a generic type from the generic type definition for a nested type, call the method with the array formed by concatenating the type argument arrays of all the enclosing types, beginning with the outermost generic type, and ending with the type argument array of the nested type itself, if it has type parameters of its own. To create an instance of `Innermost1`, call the method with an array containing three types, to be assigned to T, U, and V. To create an instance of `Innermost2`, call the method with an array containing two types, to be assigned to T and U. The languages propagate the type parameters of enclosing types in this fashion so you can use the type parameters of an enclosing type to define fields of nested types. Otherwise, the type parameters would not be in scope within the bodies of the nested types. It is possible to define nested types without propagating the type parameters of enclosing types, by emitting code in dynamic assemblies or by using the [Ilasm.exe (IL Assembler)](../../framework/tools/ilasm-exe-il-assembler.md). Consider the following code for the CIL assembler: diff --git a/docs/fundamentals/runtime-libraries/system-type.md b/docs/fundamentals/runtime-libraries/system-type.md index 6e126adaac85b..c40848e021817 100644 --- a/docs/fundamentals/runtime-libraries/system-type.md +++ b/docs/fundamentals/runtime-libraries/system-type.md @@ -43,37 +43,37 @@ This class is thread safe; multiple threads can concurrently read from an instan The object associated with a particular type can be obtained in the following ways: -- The instance method returns a object that represents the type of an instance. Because all managed types derive from , the method can be called on an instance of any type. +- The instance method returns a object that represents the type of an instance. Because all managed types derive from , the method can be called on an instance of any type. - The following example calls the method to determine the runtime type of each object in an object array. + The following example calls the method to determine the runtime type of each object in an object array. :::code language="csharp" source="./snippets/System/Type/Overview/csharp/GetType1.cs" id="Snippet2"::: :::code language="fsharp" source="./snippets/System/Type/Overview/fsharp/GetType1.fs" id="Snippet2"::: :::code language="vb" source="./snippets/System/Type/Overview/vb/GetType1.vb" id="Snippet2"::: -- The static methods return a object that represents a type specified by its fully qualified name. +- The static methods return a object that represents a type specified by its fully qualified name. -- The , , and methods return `Type` objects that represent the types defined in a module. The first method can be used to obtain an array of objects for all the public and private types defined in a module. (You can obtain an instance of `Module` through the or method, or through the property.) +- The , , and methods return `Type` objects that represent the types defined in a module. The first method can be used to obtain an array of objects for all the public and private types defined in a module. (You can obtain an instance of `Module` through the or method, or through the property.) -- The object contains a number of methods to retrieve the classes defined in an assembly, including , , and . +- The object contains a number of methods to retrieve the classes defined in an assembly, including , , and . -- The method returns a filtered list of interface types supported by a type. +- The method returns a filtered list of interface types supported by a type. -- The method returns a `Type` object that represents the element. +- The method returns a `Type` object that represents the element. -- The and methods return objects representing the interface types supported by a type. +- The and methods return objects representing the interface types supported by a type. -- The method returns an array of objects representing the types specified by an arbitrary set of objects. The objects are specified with an array of type . +- The method returns an array of objects representing the types specified by an arbitrary set of objects. The objects are specified with an array of type . -- The and methods are provided for COM interoperability. They return a object that represents the type specified by a `ProgID` or `CLSID`. +- The and methods are provided for COM interoperability. They return a object that represents the type specified by a `ProgID` or `CLSID`. -- The method is provided for interoperability. It returns a `Type` object that represents the type specified by a class handle. +- The method is provided for interoperability. It returns a `Type` object that represents the type specified by a class handle. - The C# `typeof` operator, the C++ `typeid` operator, and the Visual Basic `GetType` operator obtain the `Type` object for a type. -- The method returns a object representing a constructed generic type, which is an open constructed type if its property returns `true`, and a closed constructed type otherwise. A generic type can be instantiated only if it is closed. +- The method returns a object representing a constructed generic type, which is an open constructed type if its property returns `true`, and a closed constructed type otherwise. A generic type can be instantiated only if it is closed. -- The , , and methods return objects that represent, respectively, an array of a specified type, a pointer to a specified type, and the type of a reference parameter (`ref` in C#, 'byref' in F#, `ByRef` in Visual Basic). +- The , , and methods return objects that represent, respectively, an array of a specified type, a pointer to a specified type, and the type of a reference parameter (`ref` in C#, 'byref' in F#, `ByRef` in Visual Basic). ## Compare type objects for equality diff --git a/docs/fundamentals/runtime-libraries/system-typeinitializationexception.md b/docs/fundamentals/runtime-libraries/system-typeinitializationexception.md index 28efa6ac5ba24..54a7e109dde4c 100644 --- a/docs/fundamentals/runtime-libraries/system-typeinitializationexception.md +++ b/docs/fundamentals/runtime-libraries/system-typeinitializationexception.md @@ -17,7 +17,7 @@ Typically, the exception reflects a ca uses the HRESULT `COR_E_TYPEINITIALIZATION`, which has the value 0x80131534. -For a list of initial property values for an instance of , see the constructors. +For a list of initial property values for an instance of , see the constructors. The following sections describe some of the situations in which a exception is thrown. @@ -98,7 +98,7 @@ Most commonly, a exception is thrown w ## Regular expression match timeout values -You can set the default timeout value for a regular expression pattern matching operation on a per-application domain basis. The timeout is defined by a specifying a value for the "REGEX_DEFAULT_MATCH_TIMEOUT" property to the method. The time interval must be a valid object that is greater than zero and less than approximately 24 days. If these requirements are not met, the attempt to set the default timeout value throws an , which in turn is wrapped in a exception. +You can set the default timeout value for a regular expression pattern matching operation on a per-application domain basis. The timeout is defined by a specifying a value for the "REGEX_DEFAULT_MATCH_TIMEOUT" property to the method. The time interval must be a valid object that is greater than zero and less than approximately 24 days. If these requirements are not met, the attempt to set the default timeout value throws an , which in turn is wrapped in a exception. The following example shows the that is thrown when the value assigned to the "REGEX_DEFAULT_MATCH_TIMEOUT" property is invalid. To eliminate the exception, set the"REGEX_DEFAULT_MATCH_TIMEOUT" property to a value that is greater than zero and less than approximately 24 days. diff --git a/docs/fundamentals/runtime-libraries/system-uri.md b/docs/fundamentals/runtime-libraries/system-uri.md index fa7e940774292..184a774ee47a9 100644 --- a/docs/fundamentals/runtime-libraries/system-uri.md +++ b/docs/fundamentals/runtime-libraries/system-uri.md @@ -9,7 +9,7 @@ ms.date: 12/31/2023 A uniform resource identifier (URI) is a compact representation of a resource available to your application on the intranet or internet. The class defines the properties and methods for handling URIs, including parsing, comparing, and combining. The class properties are read-only; to create a modifiable object, use the class. -Relative URIs (for example, "/new/index.htm") must be expanded with respect to a base URI so that they are absolute. The method is provided to convert absolute URIs to relative URIs when necessary. +Relative URIs (for example, "/new/index.htm") must be expanded with respect to a base URI so that they are absolute. The method is provided to convert absolute URIs to relative URIs when necessary. The constructors do not escape URI strings if the string is a well-formed URI including a scheme identifier. @@ -47,7 +47,7 @@ AbsoluteUri: http://myurl/ PathAndQuery: / ``` -You can transform the contents of the class from an escape encoded URI reference to a readable URI reference by using the method. Note that some reserved characters might still be escaped in the output of the method. This is to support unambiguous reconstruction of a URI from the value returned by . +You can transform the contents of the class from an escape encoded URI reference to a readable URI reference by using the method. Note that some reserved characters might still be escaped in the output of the method. This is to support unambiguous reconstruction of a URI from the value returned by . Some URIs include a fragment identifier or a query or both. A fragment identifier is any text that follows a number sign (#), not including the number sign; the fragment text is stored in the property. Query information is any text that follows a question mark (?) in the URI; the query text is stored in the property. @@ -78,7 +78,7 @@ In .NET Framework 4.5 and later versions, IRI is always enabled and can't be cha Enabling IDN converts all Unicode labels in a domain name to their Punycode equivalents. Punycode names contain only ASCII characters and always start with the xn-- prefix. The reason for this is to support existing DNS servers on the Internet, since most DNS servers only support ASCII characters (see RFC 3940). -Enabling IDN affects the value of the property. Enabling IDN can also change the behavior of the , , , and methods. +Enabling IDN affects the value of the property. Enabling IDN can also change the behavior of the , , , and methods. There are three possible values for IDN depending on the DNS servers that are used: @@ -117,7 +117,7 @@ These implicit file paths are not compliant with the URI specification and shoul ## Security considerations -Because of security concerns, your application should use caution when accepting instances from untrusted sources and with `dontEscape` set to `true` in the [constructor](xref:System.Uri.%23ctor(System.String,System.Boolean)). You can check a URI string for validity by calling the method. +Because of security concerns, your application should use caution when accepting instances from untrusted sources and with `dontEscape` set to `true` in the [constructor](xref:System.Uri.%23ctor(System.String,System.Boolean)). You can check a URI string for validity by calling the method. When dealing with untrusted user input, confirm assumptions about the newly created `Uri` instance before trusting its properties. This can be done in the following way: diff --git a/docs/fundamentals/runtime-libraries/system-version.md b/docs/fundamentals/runtime-libraries/system-version.md index d88dcf2a92f3b..830550a1ea124 100644 --- a/docs/fundamentals/runtime-libraries/system-version.md +++ b/docs/fundamentals/runtime-libraries/system-version.md @@ -30,7 +30,7 @@ Subsequent versions of an assembly that differ only by build or revision numbers > [!IMPORTANT] > The value of properties that have not been explicitly assigned a value is undefined (-1). -The and properties enable you to identify a temporary version of your application that, for example, corrects a problem until you can release a permanent solution. Furthermore, the Windows NT operating system uses the property to encode the service pack number. +The and properties enable you to identify a temporary version of your application that, for example, corrects a problem until you can release a permanent solution. Furthermore, the Windows NT operating system uses the property to encode the service pack number. ## Assign version information to assemblies @@ -52,7 +52,7 @@ Ordinarily, the class is not used to assign a version numb :::code language="fsharp" source="./snippets/System/Version/Overview/fsharp/GettingVersions1.fs" id="Snippet2"::: :::code language="vb" source="./snippets/System/TypeInitializationException/Overview/vb/GettingVersions1.vb" id="Snippet2"::: -- Retrieving the current application's assembly version. The following example uses the method to obtain a reference to an object that represents the application executable and then retrieves its assembly version number. +- Retrieving the current application's assembly version. The following example uses the method to obtain a reference to an object that represents the application executable and then retrieves its assembly version number. :::code language="csharp" source="./snippets/System/Version/Overview/csharp/currentapp.cs" id="Snippet5"::: :::code language="fsharp" source="./snippets/System/Version/Overview/fsharp/currentapp.fs" id="Snippet5"::: @@ -64,7 +64,7 @@ Ordinarily, the class is not used to assign a version numb :::code language="fsharp" source="./snippets/System/Version/Overview/fsharp/currentassem.fs" id="Snippet4"::: :::code language="vb" source="./snippets/System/Version/Overview/vb/currentassem.vb" id="Snippet4"::: -- Retrieving the version of a specific assembly. The following example uses the method to obtain a reference to an object that has a particular file name, and then retrieves its version information. Note that several other methods also exist to instantiate an object by file name or by strong name. +- Retrieving the version of a specific assembly. The following example uses the method to obtain a reference to an object that has a particular file name, and then retrieves its version information. Note that several other methods also exist to instantiate an object by file name or by strong name. :::code language="csharp" source="./snippets/System/Version/Overview/csharp/specificassem.cs" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/Version/Overview/fsharp/specificassem.fs" id="Snippet3"::: @@ -80,7 +80,7 @@ Ordinarily, the class is not used to assign a version numb ## Compare version objects -You can use the method to determine whether one object is earlier than, the same as, or later than a second object. The following example indicates that Version 2.1 is later than Version 2.0. +You can use the method to determine whether one object is earlier than, the same as, or later than a second object. The following example indicates that Version 2.1 is later than Version 2.0. :::code language="csharp" source="./snippets/System/Version/Overview/csharp/comparisons1.cs" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Version/Overview/fsharp/comparisons1.fs" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-xml-linq-xname.md b/docs/fundamentals/runtime-libraries/system-xml-linq-xname.md index 6855ade184a10..ef27fb4c035a0 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-linq-xname.md +++ b/docs/fundamentals/runtime-libraries/system-xml-linq-xname.md @@ -35,7 +35,7 @@ Assigning a string to an uses the implicit conversi The Visual Basic example creates the using XML literals. Even though XML literals are used, an object is created for the . -In addition, you can call the method for an object. However, the recommended way is to use the implicit conversion from string. +In addition, you can call the method for an object. However, the recommended way is to use the implicit conversion from string. ## Create an XName in a namespace @@ -70,7 +70,7 @@ This example produces the following output: ## Create an XName in no namespace -The property of an object is guaranteed to not be null. If the is in no namespace, then the property will be set to . The following code demonstrates this: +The property of an object is guaranteed to not be null. If the is in no namespace, then the property will be set to . The following code demonstrates this: ```csharp XElement root = new XElement("ElementName", "content"); diff --git a/docs/fundamentals/runtime-libraries/system-xml-linq-xnamespace.md b/docs/fundamentals/runtime-libraries/system-xml-linq-xnamespace.md index d2e0c14756624..6cb8aee8745ce 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-linq-xnamespace.md +++ b/docs/fundamentals/runtime-libraries/system-xml-linq-xnamespace.md @@ -12,7 +12,7 @@ dev_langs: This class represents the XML construct of namespaces. -Every contains an . Even if an element is not in a namespace, the element's still contains a namespace, . The property is guaranteed to not be `null`. +Every contains an . Even if an element is not in a namespace, the element's still contains a namespace, . The property is guaranteed to not be `null`. ## Create an XNamespace object @@ -58,7 +58,7 @@ See [Work with XML namespaces](../../standard/linq/namespaces-overview.md) for m ## Control namespace prefixes -If you create an attribute that declares a namespace, the prefix specified in the attribute will be persisted in the serialized XML. To create an attribute that declares a namespace with a prefix, you create an attribute where the namespace of the name of the attribute is , and the name of the attribute is the namespace prefix. The value of the attribute is the URI of the namespace. The following example shows this idiom: +If you create an attribute that declares a namespace, the prefix specified in the attribute will be persisted in the serialized XML. To create an attribute that declares a namespace with a prefix, you create an attribute where the namespace of the name of the attribute is , and the name of the attribute is the namespace prefix. The value of the attribute is the URI of the namespace. The following example shows this idiom: ```csharp XNamespace aw = "http://www.adventure-works.com"; diff --git a/docs/fundamentals/runtime-libraries/system-xml-serialization-xmlserializer.md b/docs/fundamentals/runtime-libraries/system-xml-serialization-xmlserializer.md index e35ec642b9968..654d6175b3c10 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-serialization-xmlserializer.md +++ b/docs/fundamentals/runtime-libraries/system-xml-serialization-xmlserializer.md @@ -109,7 +109,7 @@ public class OptionalOrder You can also override the serialization of any set of objects and their fields and properties by creating one of the appropriate attributes, and adding it to an instance of the class. Overriding serialization in this way has two uses: first, you can control and augment the serialization of objects found in a DLL, even if you do not have access to the source; second, you can create one set of serializable classes, but serialize the objects in multiple ways. For more details, see the class and [How to: Control Serialization of Derived Classes](../../standard/serialization/how-to-control-serialization-of-derived-classes.md). -To serialize an object, call the method. To deserialize an object, call the method. +To serialize an object, call the method. To deserialize an object, call the method. To add XML namespaces to an XML document, see . @@ -122,9 +122,9 @@ You must have permission to write to the temporary directory (as defined by the To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. The infrastructure finds and reuses those assemblies. This behavior occurs only when using the following constructors: - + - + If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. The easiest solution is to use one of the previously mentioned two constructors. Otherwise, you must cache the assemblies in a , as shown in the following example. @@ -181,7 +181,7 @@ End If The cannot serialize or deserialize the following: - Arrays of -- Arrays of +- Arrays of ## Serialization of enumerations of unsigned Long diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmlconvert.md b/docs/fundamentals/runtime-libraries/system-xml-xmlconvert.md index 9ea149de8fc6c..a868b25e1b4d0 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmlconvert.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmlconvert.md @@ -11,11 +11,11 @@ The class is functionally equivalent to the and methods in this class to translate them into valid XML names. +Element and attribute names or ID values are limited to a range of XML characters according to the W3C [XML 1.0 recommendation](https://www.w3.org/TR/2006/REC-xml-20060816/). When names contain invalid characters, you can use the and methods in this class to translate them into valid XML names. For example, if you want to use the column heading "Order Detail" in a database, the database allows the space between the two words. However, in XML, the space between "Order" and "Detail" is considered an invalid XML character. You have to convert it into an escaped hexadecimal encoding and decode it later. -You can use the method with the class to ensure the names being written are valid XML names. The following C# code converts the name "Order Detail" into a valid XML name and writes the element `My order`. +You can use the method with the class to ensure the names being written are valid XML names. The following C# code converts the name "Order Detail" into a valid XML name and writes the element `My order`. ```csharp writer.WriteElementString(XmlConvert.EncodeName("Order Detail"),"My order"); @@ -25,20 +25,20 @@ The following methods perform encoding and decoding |Method|Description| |------------|-----------------| -||Takes a name and returns the encoded name along with any invalid character that is replaced by an escape string. This method allows colons in any position, which means that the name may still be invalid according to the W3C [Namespaces in XML 1.0 recommendation](https://www.w3.org/TR/REC-xml-names/).| -||Takes a name and returns the encoded name.| -||Same as except that it also encodes the colon character, guaranteeing that the name can be used as the `LocalName` part of a namespace-qualified name.| -||Reverses the transformation for all the encoding methods.| +||Takes a name and returns the encoded name along with any invalid character that is replaced by an escape string. This method allows colons in any position, which means that the name may still be invalid according to the W3C [Namespaces in XML 1.0 recommendation](https://www.w3.org/TR/REC-xml-names/).| +||Takes a name and returns the encoded name.| +||Same as except that it also encodes the colon character, guaranteeing that the name can be used as the `LocalName` part of a namespace-qualified name.| +||Reverses the transformation for all the encoding methods.| ## Name validation The class contains two methods that check the characters in an element or attribute name and verify that the name conforms to the rules set by the W3C [XML 1.0 recommendation](https://www.w3.org/TR/2006/REC-xml-20060816/): -- checks the characters and verifies that the name is valid. The method returns the name if it's valid, and throws an exception if it isn't. -- performs the same validation, but accepts non-qualified names. +- checks the characters and verifies that the name is valid. The method returns the name if it's valid, and throws an exception if it isn't. +- performs the same validation, but accepts non-qualified names. The contains additional methods that validate tokens, white-space characters, public IDs, and other strings. ## Data type conversion - also provides methods that enable you to convert data from a string to a strongly typed data type. For example, the method converts a string to its equivalent. This is useful because most methods in the class return data as a string. After the data is read, it can be converted to the proper data type before being used. The overloads provide the complementary operation by converting strongly typed data to strings. For example, this is useful when you want to add the data to text boxes on a webpage. Locale settings are not taken into account during data conversion. The data types are based on the XML Schema (XSD) data types. + also provides methods that enable you to convert data from a string to a strongly typed data type. For example, the method converts a string to its equivalent. This is useful because most methods in the class return data as a string. After the data is read, it can be converted to the proper data type before being used. The overloads provide the complementary operation by converting strongly typed data to strings. For example, this is useful when you want to add the data to text boxes on a webpage. Locale settings are not taken into account during data conversion. The data types are based on the XML Schema (XSD) data types. diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmldocument.md b/docs/fundamentals/runtime-libraries/system-xml-xmldocument.md index 4c9d82df3e146..0024d327182cc 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmldocument.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmldocument.md @@ -146,7 +146,7 @@ This example locates a book by using the ISBN number. The string used in this example is an Xpath query. You can find more examples of them at [XPath examples](/previous-versions/dotnet/netframework-4.0/ms256086(v=vs.100)). -You can also use the to retrieve nodes. To use this approach, you'll have to define ID's in the document type definition declarations of your XML file. +You can also use the to retrieve nodes. To use this approach, you'll have to define ID's in the document type definition declarations of your XML file. After you get a node, you get the value of attributes or child nodes. This example does that with a book node. @@ -178,11 +178,11 @@ For more information, see [Modifying Nodes, Content, and Values in an XML Docume ## Add nodes -To add a node, use the method or the method. +To add a node, use the method or the method. -To add a data node such as a book, use the method. +To add a data node such as a book, use the method. -For any other type of node such as a comment, whitespace node, or CDATA node, use the method. +For any other type of node such as a comment, whitespace node, or CDATA node, use the method. This example creates a book node, adds attributes to that node, and then adds that node to the document. @@ -193,7 +193,7 @@ For more information, see [Inserting Nodes into an XML Document](../../standard/ ## Remove nodes -To remove a node, use the method. +To remove a node, use the method. This example removes a book from the document and any whitespace that appears just before the book node. @@ -204,7 +204,7 @@ For more information, see [Removing Nodes, Content, and Values from an XML Docum ## Position nodes -You can choose where you want a node to appear in your document by using the and methods. +You can choose where you want a node to appear in your document by using the and methods. This example shows two helper methods. One of them moves a node higher in a list. The other one moves a node lower. diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmlreader-create.md b/docs/fundamentals/runtime-libraries/system-xml-xmlreader-create.md index a4a898ecece8e..1070ce3f9fe31 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmlreader-create.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmlreader-create.md @@ -10,35 +10,35 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -Most of the overloads include a `settings` parameter that accepts an object. You can use this object to: +Most of the overloads include a `settings` parameter that accepts an object. You can use this object to: - Specify which features you want supported on the object. - Reuse the object to create multiple readers. You can use the same settings to create multiple readers with the same functionality. Or, you can modify the settings on an instance and create a new reader with a different set of features. -- Add features to an existing XML reader. The method can accept another object. The underlying object can be a user-defined reader, a object, or another instance that you want to add additional features to. -- Take full advantage of features such as better conformance checking and compliance to the [XML 1.0 (fourth edition)](https://www.w3.org/TR/2006/REC-xml-20060816/) recommendation that are available only on objects created by the static method. +- Add features to an existing XML reader. The method can accept another object. The underlying object can be a user-defined reader, a object, or another instance that you want to add additional features to. +- Take full advantage of features such as better conformance checking and compliance to the [XML 1.0 (fourth edition)](https://www.w3.org/TR/2006/REC-xml-20060816/) recommendation that are available only on objects created by the static method. > [!NOTE] -> Although .NET includes concrete implementations of the class, such as the , , and the classes, we recommend that you create instances by using the method. +> Although .NET includes concrete implementations of the class, such as the , , and the classes, we recommend that you create instances by using the method. ## Default settings -If you use a overload that doesn't accept a object, the following default reader settings are used: +If you use a overload that doesn't accept a object, the following default reader settings are used: | Setting | Default | |---------------------------------------------------------------------|-------------------------------------------------------| -| | `true` | -| | | -| | `false` | -| | `false` | -| | `false` | -| | 0 | -| | 0 | -| | `null` | -| | | -| | An empty object | -| | enabled | -| | | -| | `null` | +| | `true` | +| | | +| | `false` | +| | `false` | +| | `false` | +| | 0 | +| | 0 | +| | `null` | +| | | +| | An empty object | +| | enabled | +| | | +| | `null` | ## Settings for common scenarios @@ -46,25 +46,25 @@ Here are the properties you should set for s |Requirement|Set| |-----------------|---------| -|Data must be a well-formed XML document.| to .| -|Data must be a well-formed XML parsed entity.| to .| -|Data must be validated against a DTD.| to
to .| -|Data must be validated against an XML schema.| to
to the to use for validation. Note that doesn't support XML-Data Reduced (XDR) schema validation.| -|Data must be validated against an inline XML schema.| to
to .| -|Type support.| to
to the to use.| +|Data must be a well-formed XML document.| to .| +|Data must be a well-formed XML parsed entity.| to .| +|Data must be validated against a DTD.| to
to .| +|Data must be validated against an XML schema.| to
to the to use for validation. Note that doesn't support XML-Data Reduced (XDR) schema validation.| +|Data must be validated against an inline XML schema.| to
to .| +|Type support.| to
to the to use.| doesn't support XML-Data Reduced (XDR) schema validation. ## Asynchronous programming -In synchronous mode, the method reads the first chunk of data from the buffer of the file, stream, or text reader. This may throw an exception if an I/O operation fails. In asynchronous mode, the first I/O operation occurs with a read operation, so exceptions that arise will be thrown when the read operation occurs. +In synchronous mode, the method reads the first chunk of data from the buffer of the file, stream, or text reader. This may throw an exception if an I/O operation fails. In asynchronous mode, the first I/O operation occurs with a read operation, so exceptions that arise will be thrown when the read operation occurs. ## Security considerations By default, the uses an object with no user credentials to open resources. This means that, by default, the XML reader can access any location that doesn't require credentials. Use the property to control access to resources: -- Set to an object to restrict the resources that the XML reader can access, or... -- Set to `null` to prevent the XML reader from opening any external resources. +- Set to an object to restrict the resources that the XML reader can access, or... +- Set to `null` to prevent the XML reader from opening any external resources. ## Examples diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md b/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md index 6b25e1604dc35..66f61574a3d78 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md @@ -12,7 +12,7 @@ dev_langs: provides forward-only, read-only access to XML data in a document or stream. This class conforms to the W3C [Extensible Markup Language (XML) 1.0 (fourth edition)](https://www.w3.org/TR/2006/REC-xml-20060816/) and the [Namespaces in XML 1.0 (third edition)](https://www.w3.org/TR/REC-xml-names/) recommendations. - methods let you move through XML data and read the contents of a node. The properties of the class reflect the value of the current node, which is where the reader is positioned. The property value indicates the current state of the XML reader. For example, the property is set to by the method and by the method. also provides data conformance checks and validation against a DTD or schema. + methods let you move through XML data and read the contents of a node. The properties of the class reflect the value of the current node, which is where the reader is positioned. The property value indicates the current state of the XML reader. For example, the property is set to by the method and by the method. also provides data conformance checks and validation against a DTD or schema. uses a pull model to retrieve data. This model: @@ -23,16 +23,16 @@ dev_langs: ## Create an XML reader -Use the method to create an instance. +Use the method to create an instance. Although .NET provides concrete implementations of the class, such as the , , and the classes, we recommend that you use the specialized classes only in these scenarios: - When you want to read an XML DOM subtree from an object, use the class. (However, this class doesn't support DTD or schema validation.) - If you must expand entities on request, you don't want your text content normalized, or you don't want default attributes returned, use the class. -To specify the set of features you want to enable on the XML reader, pass an object to the method. You can use a single object to create multiple readers with the same functionality, or modify the object to create a new reader with a different set of features. You can also easily add features to an existing reader. +To specify the set of features you want to enable on the XML reader, pass an object to the method. You can use a single object to create multiple readers with the same functionality, or modify the object to create a new reader with a different set of features. You can also easily add features to an existing reader. -If you don't use a object, default settings are used. See the reference page for details. +If you don't use a object, default settings are used. See the reference page for details. throws an on XML parse errors. After an exception is thrown, the state of the reader is not predictable. For example, the reported node type may be different from the actual node type of the current node. Use the property to check whether the reader is in error state. @@ -40,7 +40,7 @@ If you don't use a object (a cache); these scenarios are described on the reference page. doesn't support XML-Data Reduced (XDR) schema validation. +You can validate the data against a DTD, an inline XSD Schema, or an XSD Schema stored in an object (a cache); these scenarios are described on the reference page. doesn't support XML-Data Reduced (XDR) schema validation. You use the following settings on the class to specify what type of validation, if any, the instance supports. @@ -50,12 +50,12 @@ You use the following settings on the class | property|Whether the reader should validate data, and what type of validation to perform (DTD or schema). The default is no data validation.| | event|An event handler for receiving information about validation events. If an event handler is not provided, an is thrown on the first validation error.| | property|Additional validation options through the enumeration members:

- `AllowXmlAttributes`-- Allow XML attributes (`xml:*`) in instance documents even when they're not defined in the schema. The attributes are validated based on their data type. See the reference page for the setting to use in specific scenarios. (Disabled by default.)
- `ProcessIdentityConstraints` --Process identity constraints (`xs:ID`, `xs:IDREF`, `xs:key`, `xs:keyref`, `xs:unique`) encountered during validation. (Enabled by default.)
- `ProcessSchemaLocation` --Process schemas specified by the `xsi:schemaLocation` or `xsi:noNamespaceSchemaLocation` attribute. (Enabled by default.)
- `ProcessInlineSchema`-- Process inline XML Schemas during validation. (Disabled by default.)
- `ReportValidationWarnings`--Report events if a validation warning occurs. A warning is typically issued when there is no DTD or XML Schema to validate a particular element or attribute against. The is used for notification. (Disabled by default.)| -||The to use for validation.| +||The to use for validation.| | property|The for resolving and accessing external resources. This can include external entities such as DTD and schemas, and any `xs:include` or `xs:import` elements contained in the XML Schema. If you don't specify an , the uses a default with no user credentials.| ## Data conformance -XML readers that are created by the method meet the following compliance requirements by default: +XML readers that are created by the method meet the following compliance requirements by default: - New lines and attribute value are normalized according to the W3C [XML 1.0 Recommendation](https://www.w3.org/TR/2006/REC-xml-20060816/). @@ -71,7 +71,7 @@ Use these properties to specify the type of |Use this property|To|Default| |-------------------------------------------------------------------------------------------------------------------------------------------------------------|--------|-------------| -| property|Enable or disable checks for the following:

- Characters are within the range of legal XML characters, as defined by the [2.2 Characters](https://www.w3.org/TR/2006/REC-xml-20060816/#charsets) section of the W3C XML 1.0 Recommendation.
- All XML names are valid, as defined by the [2.3 Common Syntactic Constructs](https://www.w3.org/TR/2006/REC-xml-20060816/#NT-Name) section of the W3C XML 1.0 Recommendation.

When this property is set to `true` (default), an exception is thrown if the XML file contains illegal characters or invalid XML names (for example, an element name starts with a number).|Character and name checking is enabled.

Setting to `false` turns off character checking for character entity references. If the reader is processing text data, it always checks that XML names are valid, regardless of this setting. **Note:** The XML 1.0 recommendation requires document-level conformance when a DTD is present. Therefore, if the reader is configured to support , but the XML data contains a document type definition (DTD), an is thrown.| +| property|Enable or disable checks for the following:

- Characters are within the range of legal XML characters, as defined by the [2.2 Characters](https://www.w3.org/TR/2006/REC-xml-20060816/#charsets) section of the W3C XML 1.0 Recommendation.
- All XML names are valid, as defined by the [2.3 Common Syntactic Constructs](https://www.w3.org/TR/2006/REC-xml-20060816/#NT-Name) section of the W3C XML 1.0 Recommendation.

When this property is set to `true` (default), an exception is thrown if the XML file contains illegal characters or invalid XML names (for example, an element name starts with a number).|Character and name checking is enabled.

Setting to `false` turns off character checking for character entity references. If the reader is processing text data, it always checks that XML names are valid, regardless of this setting. **Note:** The XML 1.0 recommendation requires document-level conformance when a DTD is present. Therefore, if the reader is configured to support , but the XML data contains a document type definition (DTD), an is thrown.| | property|Choose the level of conformance to enforce:

- . Conforms to the rules for a [well-formed XML 1.0 document](https://www.w3.org/TR/2006/REC-xml-20060816/#sec-well-formed).
- . Conforms to the rules for a well-formed document fragment that can be consumed as an [external parsed entity](https://www.w3.org/TR/2006/REC-xml-20060816/#wf-entities).
- . Conforms to the level decided by the reader.

If the data isn't in conformance, an exception is thrown.|| ## Navigate through nodes @@ -82,33 +82,33 @@ The following methods make it easy to navigate through nodes and parse data. |Use this method|To| |-----------------------------------------------------------------------------------------------------------------------------------------------------------|--------| -||Read the first node, and advance through the stream one node at a time. Such calls are typically performed inside a `while` loop.

Use the property to get the type (for example, attribute, comment, element, and so on) of the current node.| -||Skip the children of the current node and move to the next node.| -| and |Skip non-content nodes and move to the next content node or to the end of the file.

Non-content nodes include , , , , and .

Content nodes include non-white space text, , , and .| -||Read an element and all its children, and return a new instance set to .

This method is useful for creating boundaries around XML elements; for example, if you want to pass data to another component for processing and you want to limit how much of your data the component can access.| +||Read the first node, and advance through the stream one node at a time. Such calls are typically performed inside a `while` loop.

Use the property to get the type (for example, attribute, comment, element, and so on) of the current node.| +||Skip the children of the current node and move to the next node.| +| and |Skip non-content nodes and move to the next content node or to the end of the file.

Non-content nodes include , , , , and .

Content nodes include non-white space text, , , and .| +||Read an element and all its children, and return a new instance set to .

This method is useful for creating boundaries around XML elements; for example, if you want to pass data to another component for processing and you want to limit how much of your data the component can access.| -See the reference page for an example of navigating through a text stream one node at a time and displaying the type of each node. +See the reference page for an example of navigating through a text stream one node at a time and displaying the type of each node. The following sections describe how you can read specific types of data, such as elements, attributes, and typed data. ## Read XML elements -The following table lists the methods and properties that the class provides for processing elements. After the is positioned on an element, the node properties, such as , reflect the element values. In addition to the members described below, any of the general methods and properties of the class can also be used to process elements. For example, you can use the method to read the contents of an element. +The following table lists the methods and properties that the class provides for processing elements. After the is positioned on an element, the node properties, such as , reflect the element values. In addition to the members described below, any of the general methods and properties of the class can also be used to process elements. For example, you can use the method to read the contents of an element. > [!NOTE] > See section 3.1 of the [W3C XML 1.0 Recommendation](https://www.w3.org/TR/2006/REC-xml-20060816/#sec-starttags) for definitions of start tags, end tags, and empty element tags. |Use this member|To| |---------------------------------------------------------------------------------------------------------------------------------------------------|--------| -| method|Check if the current node is a start tag or an empty element tag.| -| method|Check that the current node is an element and advance the reader to the next node (calls followed by ).| -| method|Check that the current node is an end tag and advance the reader to the next node.| -| method|Read a text-only element.| -| method|Advance the XML reader to the next descendant (child) element that has the specified name.| -| method|Advance the XML reader to the next sibling element that has the specified name.| -| property|Check if the current element has an end element tag. For example:

- `` ( is `true`.)
- ` ` ( is `false`, although the element's content is empty.)| +| method|Check if the current node is a start tag or an empty element tag.| +| method|Check that the current node is an element and advance the reader to the next node (calls followed by ).| +| method|Check that the current node is an end tag and advance the reader to the next node.| +| method|Read a text-only element.| +| method|Advance the XML reader to the next descendant (child) element that has the specified name.| +| method|Advance the XML reader to the next sibling element that has the specified name.| +| property|Check if the current element has an end element tag. For example:

- `` ( is `true`.)
- ` ` ( is `false`, although the element's content is empty.)| -For an example of reading the text content of elements, see the method. The following example processes elements by using a `while` loop. +For an example of reading the text content of elements, see the method. The following example processes elements by using a `while` loop. :::code language="csharp" source="./snippets/System.Xml/XmlReader/Overview/csharp/XmlReader_Basic.cs" id="Snippet10"::: :::code language="vb" source="./snippets/System.Xml/XmlReader/Overview/vb/xmlreader_basic.vb" id="Snippet10"::: @@ -117,7 +117,7 @@ For an example of reading the text content of elements, see the method lets you go through the attribute list of the element. Note that after has been called, node properties such as , , and reflect the properties of that attribute, not the properties of the element the attribute belongs to. +When positioned on an element node, the method lets you go through the attribute list of the element. Note that after has been called, node properties such as , , and reflect the properties of that attribute, not the properties of the element the attribute belongs to. The class provides these methods and properties to read and process attributes on elements. @@ -125,37 +125,37 @@ The class provides these methods and properties to r |---------------------------------------------------------------------------------------------------------------------------------------------------|--------| | property|Check whether the current node has any attributes.| | property|Get the number of attributes on the current element.| -| method|Move to the first attribute in an element.| -| method|Move to the next attribute in an element.| -| method|Move to a specified attribute.| -| method or property|Get the value of a specified attribute.| +| method|Move to the first attribute in an element.| +| method|Move to the next attribute in an element.| +| method|Move to a specified attribute.| +| method or property|Get the value of a specified attribute.| | property|Check whether the current node is an attribute that was generated from the default value defined in the DTD or schema.| -| method|Move to the element that owns the current attribute. Use this method to return to an element after navigating through its attributes.| -| method|Parse the attribute value into one or more `Text`, `EntityReference`, or `EndEntity` nodes.| +| method|Move to the element that owns the current attribute. Use this method to return to an element after navigating through its attributes.| +| method|Parse the attribute value into one or more `Text`, `EntityReference`, or `EndEntity` nodes.| -Any of the general methods and properties can also be used to process attributes. For example, after the is positioned on an attribute, the and properties reflect the values of the attribute. You can also use any of the content `Read` methods to get the value of the attribute. +Any of the general methods and properties can also be used to process attributes. For example, after the is positioned on an attribute, the and properties reflect the values of the attribute. You can also use any of the content `Read` methods to get the value of the attribute. This example uses the property to navigate through all the attributes on an element. :::code language="csharp" source="./snippets/System.Xml/XmlReader/Overview/csharp/XmlReader_Basic.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System.Xml/XmlReader/Overview/vb/xmlreader_basic.vb" id="Snippet1"::: -This example uses the method in a `while` loop to navigate through the attributes. +This example uses the method in a `while` loop to navigate through the attributes. :::code language="csharp" source="./snippets/System.Xml/XmlReader/Overview/csharp/XmlReader_Basic.cs" id="Snippet6"::: :::code language="vb" source="./snippets/System.Xml/XmlReader/Overview/vb/xmlreader_basic.vb" id="Snippet6"::: **Reading attributes on XML declaration nodes** -When the XML reader is positioned on an XML declaration node, the property returns the version, standalone, and encoding information as a single string. objects created by the method, the class, and the class expose the version, standalone, and encoding items as attributes. +When the XML reader is positioned on an XML declaration node, the property returns the version, standalone, and encoding information as a single string. objects created by the method, the class, and the class expose the version, standalone, and encoding items as attributes. **Reading attributes on document type nodes** -When the XML reader is positioned on a document type node, the method and property can be used to return the values for the SYSTEM and PUBLIC literals. For example, calling `reader.GetAttribute("PUBLIC")` returns the PUBLIC value. +When the XML reader is positioned on a document type node, the method and property can be used to return the values for the SYSTEM and PUBLIC literals. For example, calling `reader.GetAttribute("PUBLIC")` returns the PUBLIC value. **Reading attributes on processing instruction nodes** -When the is positioned on a processing instruction node, the property returns the entire text content. Items in the processing instruction node aren't treated as attributes. They can't be read with the or method. +When the is positioned on a processing instruction node, the property returns the entire text content. Items in the processing instruction node aren't treated as attributes. They can't be read with the or method. ## Read XML content @@ -163,10 +163,10 @@ The XmlReader class includes the following members that read content from an XML |Use this member|To| |---------------------------------------------------------------------------------------------------------------------------------------------------|--------| -| property|Get the text content of the current node. The value returned depends on the node type; see the reference page for details.| -| method|Get the content of an element or text node as a string. This method stops on processing instructions and comments.

For details on how this method handles specific node types, see the reference page.| -| and methods|Get all the content of the current node, including the markup, but excluding start and end tags. For example, for:

`this`

returns:

`this`| -| and methods|Get all the content of the current node and its children, including markup and start/end tags. For example, for:

`this`

returns:

`this`| +| property|Get the text content of the current node. The value returned depends on the node type; see the reference page for details.| +| method|Get the content of an element or text node as a string. This method stops on processing instructions and comments.

For details on how this method handles specific node types, see the reference page.| +| and methods|Get all the content of the current node, including the markup, but excluding start and end tags. For example, for:

`this`

returns:

`this`| +| and methods|Get all the content of the current node and its children, including markup and start/end tags. For example, for:

`this`

returns:

`this`| ## Convert to CLR types @@ -180,16 +180,16 @@ The class uses the rules defined by the [W3C XML Sch |Use this method|To return this CLR type| |--------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------| -| and || -| and || -| and || -| and || -| and || -| and || -| and |The type you specify with the `returnType` parameter| -| and |The most appropriate type, as specified by the property. See [Type Support in the System.Xml Classes](../../standard/data/xml/type-support-in-the-system-xml-classes.md) for mapping information.| +| and || +| and || +| and || +| and || +| and || +| and || +| and |The type you specify with the `returnType` parameter| +| and |The most appropriate type, as specified by the property. See [Type Support in the System.Xml Classes](../../standard/data/xml/type-support-in-the-system-xml-classes.md) for mapping information.| -If an element can't easily be converted to a CLR type because of its format, you can use a schema mapping to ensure a successful conversion. The following example uses an .xsd file to convert the `hire-date` element to the `xs:date` type, and then uses the method to return the element as a object. +If an element can't easily be converted to a CLR type because of its format, you can use a schema mapping to ensure a successful conversion. The following example uses an .xsd file to convert the `hire-date` element to the `xs:date` type, and then uses the method to return the element as a object. **Input (hireDate.xml):** @@ -212,18 +212,18 @@ Six Month Review Date: 7/8/2003 12:00:00 AM ## Asynchronous programming -Most of the methods have asynchronous counterparts that have "Async" at the end of their method names. For example, the asynchronous equivalent of is . +Most of the methods have asynchronous counterparts that have "Async" at the end of their method names. For example, the asynchronous equivalent of is . The following methods can be used with asynchronous method calls: -- -- -- -- -- -- -- -- +- +- +- +- +- +- +- +- The following sections describe asynchronous usage for methods that don't have asynchronous counterparts. @@ -258,7 +258,7 @@ Consider the following when working with the class: - Exceptions thrown from the can disclose path information that you might not want bubbled up to your app. Your app must catch exceptions and process them appropriately. -- Do not enable DTD processing if you're concerned about denial of service issues or if you're dealing with untrusted sources. DTD processing is disabled by default for objects created by the method. +- Do not enable DTD processing if you're concerned about denial of service issues or if you're dealing with untrusted sources. DTD processing is disabled by default for objects created by the method. If you have DTD processing enabled, you can use the to restrict the resources that the can access. You can also design your app so that the XML processing is memory and time constrained. For example, you can configure time-out limits in your ASP.NET app. @@ -268,7 +268,7 @@ Consider the following when working with the class: - Do not allow the to open any external resources by setting the property to `null`. -- The and validation flags of an object aren't set by default. This helps to protect the against schema-based attacks when it is processing XML data from an untrusted source. When these flags are set, the of the object is used to resolve schema locations encountered in the instance document in the . If the property is set to `null`, schema locations aren't resolved even if the and validation flags are set. +- The and validation flags of an object aren't set by default. This helps to protect the against schema-based attacks when it is processing XML data from an untrusted source. When these flags are set, the of the object is used to resolve schema locations encountered in the instance document in the . If the property is set to `null`, schema locations aren't resolved even if the and validation flags are set. Schemas added during validation add new types and can change the validation outcome of the document being validated. As a result, external schemas should only be resolved from trusted sources. @@ -282,9 +282,9 @@ Consider the following when working with the class: - Create a custom `IStream` implementation for the . -- The method can be used to handle large streams of data. This method reads a small number of characters at a time instead of allocating a single string for the whole value. +- The method can be used to handle large streams of data. This method reads a small number of characters at a time instead of allocating a single string for the whole value. -- When reading an XML document with a large number of unique local names, namespaces, or prefixes, a problem can occur. If you are using a class that derives from , and you call the , , or property for each item, the returned string is added to a . The collection held by the never decreases in size, creating a virtual memory leak of the string handles. One mitigation for this is to derive from the class and enforce a maximum size quota. (There is no way to prevent the use of a , or to switch the when it is full). Another mitigation is to avoid using the properties mentioned and instead use the method with the method where possible; those methods don't return strings and thus avoid the problem of overfilling the collection. +- When reading an XML document with a large number of unique local names, namespaces, or prefixes, a problem can occur. If you are using a class that derives from , and you call the , , or property for each item, the returned string is added to a . The collection held by the never decreases in size, creating a virtual memory leak of the string handles. One mitigation for this is to derive from the class and enforce a maximum size quota. (There is no way to prevent the use of a , or to switch the when it is full). Another mitigation is to avoid using the properties mentioned and instead use the method with the method where possible; those methods don't return strings and thus avoid the problem of overfilling the collection. - objects can contain sensitive information such as user credentials. An untrusted component could use the object and its user credentials to create objects to read data. Be careful when caching objects, or when passing the object from one component to another. diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-dtdprocessing.md b/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-dtdprocessing.md index 2607b5566e76c..6a71ce9ab1e60 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-dtdprocessing.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-dtdprocessing.md @@ -17,9 +17,9 @@ The property can have one of t To perform validation against a DTD, the uses the DTD defined in the DOCTYPE declaration of an XML document. The DOCTYPE declaration can either point to an inline DTD or can be a reference to an external DTD file. To validate an XML file against a DTD: -- Set the property to `DtdProcessing.Parse`. -- Set the property to `ValidationType.DTD`. -- If the DTD is an external file stored on a network resource that requires authentication, pass an object with the necessary credentials to the method. +- Set the property to `DtdProcessing.Parse`. +- Set the property to `ValidationType.DTD`. +- If the DTD is an external file stored on a network resource that requires authentication, pass an object with the necessary credentials to the method. > [!IMPORTANT] > If the property is set to , the will not report the DTDs. This means that the DTD/DOCTYPE will be lost on output. diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-schemas.md b/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-schemas.md index c48f98a396a7e..db513d5a90144 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-schemas.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-schemas.md @@ -16,10 +16,10 @@ This article pertains to the propert > - Schema validation error messages and exceptions may expose sensitive information about the content model or URI paths to the schema file. Be careful not to expose this information to untrusted callers. > - For additional information, see the "Security considerations" section. -The class only supports XML Schema definition language (XSD) schemas. instances created by the method cannot be configured to enable XML-Data Reduced (XDR) schema validation. +The class only supports XML Schema definition language (XSD) schemas. instances created by the method cannot be configured to enable XML-Data Reduced (XDR) schema validation. ## Security considerations -- Do not use schemas from unknown or untrusted sources. Doing so will compromise the security of your code. The class is used to resolve external schemas by default. To disable resolution of include, import, and redefine elements of a schema, set the property to `null`. +- Do not use schemas from unknown or untrusted sources. Doing so will compromise the security of your code. The class is used to resolve external schemas by default. To disable resolution of include, import, and redefine elements of a schema, set the property to `null`. - Exceptions raised as a result of using the class, such as the class may contain sensitive information that should not be exposed in untrusted scenarios. For example, the property of an returns the URI path to the schema file that caused the exception. The property should not be exposed in untrusted scenarios. Exceptions should be properly handled so that this sensitive information is not exposed in untrusted scenarios. diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings.md b/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings.md index 7238e80cf7b97..145f8ea5615f8 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings.md @@ -7,15 +7,15 @@ ms.date: 12/31/2023 [!INCLUDE [context](includes/context.md)] -You use the method to obtain instances. This method uses the class to specify which features to implement in the object it creates. +You use the method to obtain instances. This method uses the class to specify which features to implement in the object it creates. -See the Remarks sections of the and reference pages for information about which settings to use for conformance checks, validation, and other common scenarios. See the constructor for a list of default settings. +See the Remarks sections of the and reference pages for information about which settings to use for conformance checks, validation, and other common scenarios. See the constructor for a list of default settings. ## Security considerations Consider the following when using the class. -- The and validation flags of an object are not set by default. When these flags are set, the of the object is used to resolve schema locations encountered in the instance document in the . If the object is `null`, schema locations are not resolved even if the and validation flags are set. +- The and validation flags of an object are not set by default. When these flags are set, the of the object is used to resolve schema locations encountered in the instance document in the . If the object is `null`, schema locations are not resolved even if the and validation flags are set. - Schemas added during validation add new types and can change the validation outcome of the document being validated. As a result, external schemas should only be resolved from trusted sources. diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmlresolver.md b/docs/fundamentals/runtime-libraries/system-xml-xmlresolver.md index 23412795efd2e..4e69485cc17b7 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmlresolver.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmlresolver.md @@ -22,7 +22,7 @@ The namespace includes two concrete implementations of the with no user credentials. -You specify the to use by setting the property and passing the object to the method. +You specify the to use by setting the property and passing the object to the method. If the resource is stored on a system that requires authentication, you use the property to specify the necessary credentials. @@ -48,6 +48,6 @@ Consider the following items when working with the - If you are designing a class property that uses the class, the property should be defined as a write-only property. The property can be used to specify the to use, but it cannot be used to return an object. -- If your application accepts objects from untrusted code, you cannot assume that the URI passed into the method will be the same as that returned by the method. Classes derived from the class can override the method and return data that is different than what was contained in the original URI. +- If your application accepts objects from untrusted code, you cannot assume that the URI passed into the method will be the same as that returned by the method. Classes derived from the class can override the method and return data that is different than what was contained in the original URI. -- Your application can mitigate memory denial of service threats to the method by implementing an that limits the number of bytes read. This helps guard against situations where malicious code attempts to pass an infinite stream of bytes to the method. +- Your application can mitigate memory denial of service threats to the method by implementing an that limits the number of bytes read. This helps guard against situations where malicious code attempts to pass an infinite stream of bytes to the method. diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmlsecureresolver.md b/docs/fundamentals/runtime-libraries/system-xml-xmlsecureresolver.md index 19a63521e6274..8f3d0c16a5ef7 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmlsecureresolver.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmlsecureresolver.md @@ -16,13 +16,13 @@ You can override this default by specifying the ob wraps around a concrete implementation of and restricts the resources that the underlying has access to. For example, has the ability to prohibit cross-domain redirection, which occurs from an embedded Uniform Resource Identifier (URI) reference. -When you construct an object, you provide a valid implementation along with a URL, an instance of an evidence object, or a permission set, which is used by the to determine security. Either a is generated or the existing one is used and is called on it to help secure the underlying . +When you construct an object, you provide a valid implementation along with a URL, an instance of an evidence object, or a permission set, which is used by the to determine security. Either a is generated or the existing one is used and is called on it to help secure the underlying . > [!IMPORTANT] > objects can contain sensitive information such as user credentials. Be careful when caching objects and should not pass the object to an untrusted component. > [!IMPORTANT] -> There are differences in the security infrastructure for code running on the .NET common language runtime (CLR) and for code running on the CLR that is integrated within Microsoft SQL Server 2005. This can lead to cases where code developed for the .NET CLR operates differently when used on the SQL Server integrated CLR. One of these differences affects the class when you have evidence that is based on a URL (that is, when you use the method or the constructor). The policy resolution mechanism of the SQL Server integrated CLR does not use the or information. Instead, it grants permissions based on the GUID that the server adds when assemblies are loaded. When you use the in the SQL Server integrated CLR, provide any required evidence directly by using a specified . +> There are differences in the security infrastructure for code running on the .NET common language runtime (CLR) and for code running on the CLR that is integrated within Microsoft SQL Server 2005. This can lead to cases where code developed for the .NET CLR operates differently when used on the SQL Server integrated CLR. One of these differences affects the class when you have evidence that is based on a URL (that is, when you use the method or the constructor). The policy resolution mechanism of the SQL Server integrated CLR does not use the or information. Instead, it grants permissions based on the GUID that the server adds when assemblies are loaded. When you use the in the SQL Server integrated CLR, provide any required evidence directly by using a specified . ## To use a secure resolver @@ -33,14 +33,14 @@ When you construct an object, you provide a :::code language="csharp" source="./snippets/System.Xml/XmlSecureResolver/Overview/csharp/XmlSecureResolver_ex.cs" id="Snippet5a"::: :::code language="vb" source="./snippets/System.Xml/XmlSecureResolver/Overview/vb/XmlSecureResolver_ex.vb" id="Snippet5a"::: -3. Pass the object to the method when you're creating the object. +3. Pass the object to the method when you're creating the object. :::code language="csharp" source="./snippets/System.Xml/XmlSecureResolver/Overview/csharp/XmlSecureResolver_ex.cs" id="Snippet5b"::: :::code language="vb" source="./snippets/System.Xml/XmlSecureResolver/Overview/vb/XmlSecureResolver_ex.vb" id="Snippet5b"::: ## To restrict access by using a URL -Use the constructor to create an object that is allowed to access your local intranet site only. +Use the constructor to create an object that is allowed to access your local intranet site only. :::code language="csharp" source="./snippets/System.Xml/XmlSecureResolver/Overview/csharp/XmlSecureResolver_ex.cs" id="Snippet3"::: :::code language="vb" source="./snippets/System.Xml/XmlSecureResolver/Overview/vb/XmlSecureResolver_ex.vb" id="Snippet3"::: @@ -62,16 +62,16 @@ Use the constructor to create an object by using the permission set. +4. Use the constructor to create an object by using the permission set. :::code language="csharp" source="./snippets/System.Xml/XmlSecureResolver/Overview/csharp/XmlSecureResolver_ex.cs" id="Snippet4d"::: :::code language="vb" source="./snippets/System.Xml/XmlSecureResolver/Overview/vb/XmlSecureResolver_ex.vb" id="Snippet4d"::: - See the reference page for another example. + See the reference page for another example. ## To restrict access by using evidence -You can restrict access by using the constructor and specifying . The is used to create the that is applied to the underlying . The calls on the created before opening any resources. +You can restrict access by using the constructor and specifying . The is used to create the that is applied to the underlying . The calls on the created before opening any resources. Here are some common scenarios and the type of evidence to provide for each: @@ -97,7 +97,7 @@ Here are some common scenarios and the type of evidence to provide for each: 1. Create an with the correct permission set. -2. Pass the to the method. +2. Pass the to the method. :::code language="csharp" source="./snippets/System.Xml/XmlSecureResolver/Overview/csharp/XmlSecureResolver_ex.cs" id="Snippet6"::: :::code language="vb" source="./snippets/System.Xml/XmlSecureResolver/Overview/vb/XmlSecureResolver_ex.vb" id="Snippet6"::: diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmltextreader.md b/docs/fundamentals/runtime-libraries/system-xml-xmltextreader.md index 2b1c7271d39f4..b0da84c203b82 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmltextreader.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmltextreader.md @@ -8,7 +8,7 @@ ms.date: 12/31/2023 [!INCLUDE [context](includes/context.md)] > [!NOTE] -> We recommend that you create instances by using the method to take advantage of new functionality. +> We recommend that you create instances by using the method to take advantage of new functionality. provides forward-only, read-only access to a stream of XML data. The current node refers to the node on which the reader is positioned. The reader is advanced using any of the read methods and properties reflect the value of the current node. @@ -20,7 +20,7 @@ This class implements and conforms to the W3C Extens - Checks that `DocumentType` nodes are well-formed. `XmlTextReader` checks the DTD for well-formedness, but does not validate using the DTD. -- For nodes where is `XmlNodeType.EntityReference`, a single empty `EntityReference` node is returned (that is, the property is `String.Empty`). +- For nodes where is `XmlNodeType.EntityReference`, a single empty `EntityReference` node is returned (that is, the property is `String.Empty`). > [!NOTE] > The actual declarations of entities in the DTD are called `Entity` nodes. When you refer to these nodes in your data, they are called `EntityReference` nodes. @@ -53,6 +53,6 @@ The following are things to consider when using the , create a custom IStream implementation and supply it the . -- The method can be used to handle large streams of data. This method reads a small number of characters at a time instead of allocating a single string for the whole value. +- The method can be used to handle large streams of data. This method reads a small number of characters at a time instead of allocating a single string for the whole value. -- By default general entities are not expanded. General entities are expanded when you call the method. +- By default general entities are not expanded. General entities are expanded when you call the method. diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmltextwriter.md b/docs/fundamentals/runtime-libraries/system-xml-xmltextwriter.md index 2c9c4d7d52869..455b66923eb24 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmltextwriter.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmltextwriter.md @@ -10,7 +10,7 @@ ms.date: 12/31/2023 The class implements the class. > [!NOTE] -> We recommend that you create instances by using the method and the class to take advantage of new functionality. +> We recommend that you create instances by using the method and the class to take advantage of new functionality. `XmlTextWriter` maintains a namespace stack corresponding to all the namespaces defined in the current element stack. Using `XmlTextWriter` you can declare namespaces manually. @@ -100,9 +100,9 @@ The following items are things to consider when working with the can disclose path information that you do not want bubbled up to the application. Your applications must catch exceptions and process them appropriately. -- When you pass the to another application the underlying stream is exposed to that application. If you need to pass the to a semi-trusted application, you should use an object created by the method instead. +- When you pass the to another application the underlying stream is exposed to that application. If you need to pass the to a semi-trusted application, you should use an object created by the method instead. -- The does not validate any data that is passed to the or methods. You should not pass arbitrary data to these methods. +- The does not validate any data that is passed to the or methods. You should not pass arbitrary data to these methods. - If the default settings are changed, there is no guarantee that the generated output is well-formed XML data. diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmlwriter.md b/docs/fundamentals/runtime-libraries/system-xml-xmlwriter.md index 9e3e8c8cb5fc9..69a2f9e07f234 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmlwriter.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmlwriter.md @@ -21,7 +21,7 @@ The members of the class enable you to: ## Create an XML writer -To create an instance, use the method. To specify the set of features you want to enable on the XML writer, pass an to the method. Otherwise, default settings are used. See the reference pages for details. +To create an instance, use the method. To specify the set of features you want to enable on the XML writer, pass an to the method. Otherwise, default settings are used. See the reference pages for details. ## Specify the output format @@ -29,20 +29,20 @@ The class includes several properties that c |Property|Description| |--------------|-----------------| -||Specifies the text encoding to use. The default is `Encoding.UTF8`.| -||Indicates whether to indent elements. The default is `false` (no indentation).| -||Specifies the character string to use when indenting. The default is two spaces.| -||Specifies the character string to use for line breaks. The default is `\r\n` (carriage return, line feed) for non-Unix platforms, and `\n` (line feed) for Unix platforms.| -||Specifies how to handle newline characters.| -||Indicates whether to write attributes on a new line. should be set to `true` when using this property. The default is `false`.| -||Indicates whether to write an XML declaration. The default is `false`.| +||Specifies the text encoding to use. The default is `Encoding.UTF8`.| +||Indicates whether to indent elements. The default is `false` (no indentation).| +||Specifies the character string to use when indenting. The default is two spaces.| +||Specifies the character string to use for line breaks. The default is `\r\n` (carriage return, line feed) for non-Unix platforms, and `\n` (line feed) for Unix platforms.| +||Specifies how to handle newline characters.| +||Indicates whether to write attributes on a new line. should be set to `true` when using this property. The default is `false`.| +||Indicates whether to write an XML declaration. The default is `false`.| -The and properties control how insignificant white space is formatted. For example, to indent element nodes: +The and properties control how insignificant white space is formatted. For example, to indent element nodes: :::code language="csharp" source="./snippets/System.Xml/XmlWriter/Overview/csharp/writer_v2.cs" id="Snippet8"::: :::code language="vb" source="./snippets/System.Xml/XmlWriter/Overview/vb/writer_v2.vb" id="Snippet8"::: -Use the to write each attribute on a new line with one extra level of indentation: +Use the to write each attribute on a new line with one extra level of indentation: :::code language="csharp" source="./snippets/System.Xml/XmlWriter/Overview/csharp/writer_v2.cs" id="Snippet9"::: :::code language="vb" source="./snippets/System.Xml/XmlWriter/Overview/vb/writer_v2.vb" id="Snippet9"::: @@ -67,9 +67,9 @@ You can use the following methods to write element n |Use|To| |---------|--------| -||Write an entire element node, including a string value.| -||To write an element value by using multiple method calls. For example, you can call to write a typed value, to write a character entity, to write an attribute, or you can write a child element. This is a more sophisticated version of the method.

To close the element, you call the or method.| -||To copy an element node found at the current position of an or object. When called, it copies everything from the source object to the instance.| +||Write an entire element node, including a string value.| +||To write an element value by using multiple method calls. For example, you can call to write a typed value, to write a character entity, to write an attribute, or you can write a child element. This is a more sophisticated version of the method.

To close the element, you call the or method.| +||To copy an element node found at the current position of an or object. When called, it copies everything from the source object to the instance.| ## Write attributes @@ -77,9 +77,9 @@ You can use the following methods to write attribute |Use|To| |---------|--------| -||To write an entire attribute node, including a string value.| -||To write the attribute value using multiple method calls. For example, you can call to write a typed value. This is a more sophisticated version of the method.

To close the element, you call the method.| -||To copy all the attributes found at the current position of an object. The attributes that are written depend on the type of node the reader is currently positioned on:

- For an attribute node, it writes the current attribute, and then the rest of the attributes until the element closing tag.
- For an element node, it writes all attributes contained by the element.
- For an XML declaration node, it writes all the attributes in the declaration.
- For all other node types, the method throws an exception.| +||To write an entire attribute node, including a string value.| +||To write the attribute value using multiple method calls. For example, you can call to write a typed value. This is a more sophisticated version of the method.

To close the element, you call the method.| +||To copy all the attributes found at the current position of an object. The attributes that are written depend on the type of node the reader is currently positioned on:

- For an attribute node, it writes the current attribute, and then the rest of the attributes until the element closing tag.
- For an element node, it writes all attributes contained by the element.
- For an XML declaration node, it writes all the attributes in the declaration.
- For all other node types, the method throws an exception.| ## Handle namespaces @@ -87,9 +87,9 @@ Namespaces are used to qualify element and attribute names in an XML document. N The maintains a namespace stack that corresponds to all the namespaces defined in the current namespace scope. When writing elements and attributes you can utilize namespaces in the following ways: -- Declare namespaces manually by using the method. This can be useful when you know how to best optimize the number of namespace declarations. For an example, see the method. +- Declare namespaces manually by using the method. This can be useful when you know how to best optimize the number of namespace declarations. For an example, see the method. -- Override the current namespace declaration with a new namespace. In the following code, the method changes the namespace URI for the `"x"` prefix from `"123"` to `"abc"`. +- Override the current namespace declaration with a new namespace. In the following code, the method changes the namespace URI for the `"x"` prefix from `"123"` to `"abc"`. :::code language="csharp" source="./snippets/System.Xml/XmlWriter/Overview/csharp/writer_v2.cs" id="Snippet18"::: :::code language="vb" source="./snippets/System.Xml/XmlWriter/Overview/vb/writer_v2.vb" id="Snippet18"::: @@ -102,27 +102,27 @@ The maintains a namespace stack that corresponds to ``` -- Specify a namespace prefix when writing attributes or elements. Many of the methods used to write element and attributes enable you to do this. For example, the method writes a start tag and associates it with a specified namespace and prefix. +- Specify a namespace prefix when writing attributes or elements. Many of the methods used to write element and attributes enable you to do this. For example, the method writes a start tag and associates it with a specified namespace and prefix. ## Write typed data -The method accepts a common language runtime (CLR) object, converts the input value to its string representation according to XML schema definition language (XSD) data type conversion rules, and writes it out by using the method. This is easier than using the methods in the class to convert the typed data to a string value before writing it out. +The method accepts a common language runtime (CLR) object, converts the input value to its string representation according to XML schema definition language (XSD) data type conversion rules, and writes it out by using the method. This is easier than using the methods in the class to convert the typed data to a string value before writing it out. When writing to text, the typed value is serialized to text by using the rules for that schema type. -For default XSD data types that correspond to CLR types, see the method. +For default XSD data types that correspond to CLR types, see the method. -The can also be used to write to an XML data store. For example, the class can create an object to create nodes for an object. If the data store has schema information available to it, the method throws an exception if you try to convert to a type that is not allowed. If the data store does not have schema information available to it, the method treats all values as an `xsd:anySimpleType` type. +The can also be used to write to an XML data store. For example, the class can create an object to create nodes for an object. If the data store has schema information available to it, the method throws an exception if you try to convert to a type that is not allowed. If the data store does not have schema information available to it, the method treats all values as an `xsd:anySimpleType` type. ## Close the XML writer -When you use methods to output XML, the elements and attributes are not written until you call the method. For example, if you are using to populate an object, you won't be able to see the written elements and attributes in the target document until you close the instance. +When you use methods to output XML, the elements and attributes are not written until you call the method. For example, if you are using to populate an object, you won't be able to see the written elements and attributes in the target document until you close the instance. ## Asynchronous programming -Most of the methods have asynchronous counterparts that have "Async" at the end of their method names. For example, the asynchronous equivalent of is . +Most of the methods have asynchronous counterparts that have "Async" at the end of their method names. For example, the asynchronous equivalent of is . -For the method, which doesn't have an asynchronous counterpart, convert the return value to a string and use the method instead. +For the method, which doesn't have an asynchronous counterpart, convert the return value to a string and use the method instead. ## Security considerations @@ -130,4 +130,4 @@ Consider the following when working with the class: - Exceptions thrown by the can disclose path information that you do not want bubbled up to the app. Your app must catch exceptions and process them appropriately. -- does not validate any data that is passed to the or method. You should not pass arbitrary data to these methods. +- does not validate any data that is passed to the or method. You should not pass arbitrary data to these methods. diff --git a/docs/fundamentals/runtime-libraries/system-xml-xsl-xslcompiledtransform.md b/docs/fundamentals/runtime-libraries/system-xml-xsl-xslcompiledtransform.md index 302c79575eaae..109df99bb3454 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xsl-xslcompiledtransform.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xsl-xslcompiledtransform.md @@ -7,9 +7,9 @@ ms.date: 12/31/2023 [!INCLUDE [context](includes/context.md)] -The class is an XSLT processor that supports the XSLT 1.0 syntax. It is a new implementation and includes performance gains when compared to the obsolete class. The structure of the class is very similar to the class. The method loads and compiles the style sheet, while the method executes the XSLT transform. +The class is an XSLT processor that supports the XSLT 1.0 syntax. It is a new implementation and includes performance gains when compared to the obsolete class. The structure of the class is very similar to the class. The method loads and compiles the style sheet, while the method executes the XSLT transform. -Support for the XSLT `document()` function and embedded script blocks are disabled by default. These features can be enabled by creating an object and passing it to the method. +Support for the XSLT `document()` function and embedded script blocks are disabled by default. These features can be enabled by creating an object and passing it to the method. For more information, see [Using the XslCompiledTransform Class](../../standard/data/xml/using-the-xslcompiledtransform-class.md) and [Migrating From the XslTransform Class](../../standard/data/xml/migrating-from-the-xsltransform-class.md). @@ -19,12 +19,12 @@ When creating an application that uses the object to the method. +- The XSLT `document()` function is disabled by default. If you enable the `document()` function, restrict the resources that can be accessed by passing an object to the method. -- Extension objects are enabled by default. If an object containing extension objects is passed to the method, they are utilized. +- Extension objects are enabled by default. If an object containing extension objects is passed to the method, they are utilized. - XSLT style sheets can include references to other files and embedded script blocks. A malicious user can exploit this by supplying you with data or style sheets that when executed can cause your system to process until the computer runs low on resources. -- XSLT applications that run in a mixed trust environment can result in style sheet spoofing. For example, a malicious user can load an object with a harmful style sheet and hand it off to another user who subsequently calls the method and executes the transformation. +- XSLT applications that run in a mixed trust environment can result in style sheet spoofing. For example, a malicious user can load an object with a harmful style sheet and hand it off to another user who subsequently calls the method and executes the transformation. These security issues can be mitigated by not enabling scripting or the `document()` function unless the style sheet comes from a trusted source, and by not accepting objects, XSLT style sheets, or XML source data from an untrusted source. From 167f75f69dfba32c6d8725a94bd5a3a7d104bd14 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 9 Feb 2026 17:21:33 -0800 Subject: [PATCH 3/7] properties don't have overloads --- .../includes/stringbuilder-perf-note.md | 4 +- .../system-collections-generic-list{t}.md | 4 +- .../runtime-libraries/system-console.md | 8 ++-- .../runtime-libraries/system-data-dataset.md | 2 +- .../system-data-datatable.md | 4 +- .../system-globalization-compareinfo.md | 2 +- .../system-globalization-cultureinfo.md | 10 ++--- ...system-globalization-datetimeformatinfo.md | 38 +++++++++---------- .../system-globalization-sortkey.md | 2 +- .../system-globalization-sortversion.md | 4 +- .../runtime-libraries/system-string.md | 2 +- .../system-text-stringbuilder.md | 8 ++-- .../runtime-libraries/system-xml-xmlreader.md | 4 +- 13 files changed, 46 insertions(+), 46 deletions(-) diff --git a/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md b/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md index 59b297b5d3fa0..7490f241b3716 100644 --- a/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md +++ b/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md @@ -1,4 +1,4 @@ -Using character-based indexing with the property can be extremely slow under the following conditions: +Using character-based indexing with the property can be extremely slow under the following conditions: - The instance is large (for example, it consists of several tens of thousands of characters). - The is "chunky." That is, repeated calls to methods such as have automatically expanded the object's property and allocated new chunks of memory to it. @@ -6,7 +6,7 @@ Using character-based indexing with the Performance is severely impacted because each character access walks the entire linked list of chunks to find the correct buffer to index into. > [!NOTE] -> Even for a large "chunky" object, using the property for index-based access to one or a small number of characters has a negligible performance impact; typically, it is an **O(n)** operation. The significant performance impact occurs when iterating the characters in the object, which is an **O(n^2)** operation. +> Even for a large "chunky" object, using the property for index-based access to one or a small number of characters has a negligible performance impact; typically, it is an **O(n)** operation. The significant performance impact occurs when iterating the characters in the object, which is an **O(n^2)** operation. If you encounter performance issues when using character-based indexing with objects, you can use any of the following workarounds: diff --git a/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md b/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md index 4fd286340ceee..d0c859a17ff4d 100644 --- a/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md +++ b/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md @@ -55,11 +55,11 @@ The following example demonstrates how to add, remove, and insert a simple busin The following example demonstrates several properties and methods of the generic class of type string. (For an example of a of complex types, see the method.) -The parameterless constructor is used to create a list of strings with the default capacity. The property is displayed and then the method is used to add several items. The items are listed, and the property is displayed again, along with the property, to show that the capacity has been increased as needed. +The parameterless constructor is used to create a list of strings with the default capacity. The property is displayed and then the method is used to add several items. The items are listed, and the property is displayed again, along with the property, to show that the capacity has been increased as needed. The method is used to test for the presence of an item in the list, the method is used to insert a new item in the middle of the list, and the contents of the list are displayed again. -The default property (the indexer in C#) is used to retrieve an item, the method is used to remove the first instance of the duplicate item added earlier, and the contents are displayed again. The method always removes the first instance it encounters. +The default property (the indexer in C#) is used to retrieve an item, the method is used to remove the first instance of the duplicate item added earlier, and the contents are displayed again. The method always removes the first instance it encounters. The method is used to reduce the capacity to match the count, and the and properties are displayed. If the unused capacity had been less than 10 percent of total capacity, the list would not have been resized. diff --git a/docs/fundamentals/runtime-libraries/system-console.md b/docs/fundamentals/runtime-libraries/system-console.md index ef3da157114e9..c0c8aa9ac7e86 100644 --- a/docs/fundamentals/runtime-libraries/system-console.md +++ b/docs/fundamentals/runtime-libraries/system-console.md @@ -17,7 +17,7 @@ The console is an operating system window where users interact with the operatin When a console application starts, the operating system automatically associates three I/O streams with the console: standard input stream, standard output stream, and standard error output stream. Your application can read user input from the standard input stream; write normal data to the standard output stream; and write error data to the standard error output stream. These streams are presented to your application as the values of the , , and properties. -By default, the value of the property is a object that represents the keyboard, and the values of the and properties are objects that represent a console window. However, you can set these properties to streams that do not represent the console window or keyboard; for example, you can set these properties to streams that represent files. To redirect the standard input, standard output, or standard error stream, call the , , or method, respectively. I/O operations that use these streams are synchronized, which means that multiple threads can read from, or write to, the streams. This means that methods that are ordinarily asynchronous, such as , execute synchronously if the object represents a console stream. +By default, the value of the property is a object that represents the keyboard, and the values of the and properties are objects that represent a console window. However, you can set these properties to streams that do not represent the console window or keyboard; for example, you can set these properties to streams that represent files. To redirect the standard input, standard output, or standard error stream, call the , , or method, respectively. I/O operations that use these streams are synchronized, which means that multiple threads can read from, or write to, the streams. This means that methods that are ordinarily asynchronous, such as , execute synchronously if the object represents a console stream. > [!NOTE] > Do not use the class to display output in unattended applications, such as server applications. Calls to methods such as and have no effect in GUI applications. @@ -26,7 +26,7 @@ By default, the value of the property is a , , and properties. For example, by default, the method reads input from the standard input stream. Similarly, the method writes data to the standard output stream, and the data is followed by the default line termination string, which can be found at . However, the class does not provide a corresponding method to write data to the standard error output stream, or a property to change the line termination string for data written to that stream. -You can solve this problem by setting the property of the or property to another line termination string. For example, the following C# statement sets the line termination string for the standard error output stream to two carriage return and line feed sequences: +You can solve this problem by setting the property of the or property to another line termination string. For example, the following C# statement sets the line termination string for the standard error output stream to two carriage return and line feed sequences: `Console.Error.NewLine = "\r\n\r\n";` @@ -52,7 +52,7 @@ In general, the console reads input and writes output by using the current conso :::code language="vb" source="./snippets/System/Console/Overview/vb/unicode1.vb" id="Snippet1"::: :::code language="fsharp" source="./snippets/System/Console/Overview/fsharp/unicode1.fs" id="Snippet1"::: -In addition to supporting code pages, the class supports UTF-8 encoding with the class. Beginning with .NET Framework 4.5, the class also supports UTF-16 encoding with the class. To display Unicode characters to the console. you set the property to either or . +In addition to supporting code pages, the class supports UTF-8 encoding with the class. Beginning with .NET Framework 4.5, the class also supports UTF-16 encoding with the class. To display Unicode characters to the console. you set the property to either or . Support for Unicode characters requires the encoder to recognize a particular Unicode character, and also requires a font that has the glyphs needed to render that character. To successfully display Unicode characters to the console, the console font must be set to a non-raster or TrueType font such as Consolas or Lucida Console. The following example shows how you can programmatically change the font from a raster font to Lucida Console. @@ -112,7 +112,7 @@ The class also contains methods and properties to perform - Get or set the size of the console window. The and properties let you get or set the window height and width, respectively, and the method lets you set the window size in a single method call. -- Get or set the size of the cursor. The property specifies the height of the cursor in a character cell. +- Get or set the size of the cursor. The property specifies the height of the cursor in a character cell. - Get or set the position of the console window relative to the screen buffer. The and properties let you get or set the top row and leftmost column of the screen buffer that appears in the console window, and the method lets you set these values in a single method call. diff --git a/docs/fundamentals/runtime-libraries/system-data-dataset.md b/docs/fundamentals/runtime-libraries/system-data-dataset.md index 119f8d780a9d1..7bc31be686aaf 100644 --- a/docs/fundamentals/runtime-libraries/system-data-dataset.md +++ b/docs/fundamentals/runtime-libraries/system-data-dataset.md @@ -9,7 +9,7 @@ ms.date: 01/02/2024 The class, which is an in-memory cache of data retrieved from a data source, is a major component of the ADO.NET architecture. The consists of a collection of objects that you can relate to each other with objects. You can also enforce data integrity in the by using the and objects. For further details about working with objects, see [DataSets, DataTables, and DataViews](../../framework/data/adonet/dataset-datatable-dataview/index.md). -Whereas objects contain the data, the allows you to navigate though the table hierarchy. The tables are contained in a accessed through the property. When accessing objects, note that they are conditionally case sensitive. For example, if one is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. For more information about working with objects, see [Creating a DataTable](../../framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md). +Whereas objects contain the data, the allows you to navigate though the table hierarchy. The tables are contained in a accessed through the property. When accessing objects, note that they are conditionally case sensitive. For example, if one is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. For more information about working with objects, see [Creating a DataTable](../../framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md). A can read and write data and schema as XML documents. The data and schema can then be transported across HTTP and used by any application, on any platform that is XML-enabled. You can save the schema as an XML schema with the method, and both schema and data can be saved using the method. To read an XML document that includes both schema and data, use the method. diff --git a/docs/fundamentals/runtime-libraries/system-data-datatable.md b/docs/fundamentals/runtime-libraries/system-data-datatable.md index 7ab25d9281874..3534a00e05884 100644 --- a/docs/fundamentals/runtime-libraries/system-data-datatable.md +++ b/docs/fundamentals/runtime-libraries/system-data-datatable.md @@ -12,9 +12,9 @@ dev_langs: The class is a central object in the ADO.NET library. Other objects that use include the and the . - object names are conditionally case sensitive. For example, if one is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. A can contain two objects that have the same property value but different property values. For more information about working with objects, see [Creating a DataTable](../../framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md). + object names are conditionally case sensitive. For example, if one is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. A can contain two objects that have the same property value but different property values. For more information about working with objects, see [Creating a DataTable](../../framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md). -If you're creating a programmatically, you must first define its schema by adding objects to the (accessed through the property). For more information about adding objects, see [Adding Columns to a DataTable](../../framework/data/adonet/dataset-datatable-dataview/adding-columns-to-a-datatable.md). +If you're creating a programmatically, you must first define its schema by adding objects to the (accessed through the property). For more information about adding objects, see [Adding Columns to a DataTable](../../framework/data/adonet/dataset-datatable-dataview/adding-columns-to-a-datatable.md). To add rows to a , you must first use the method to return a new object. The method returns a row with the schema of the , as it is defined by the table's . The maximum number of rows that a can store is 16,777,216. For more information, see [Adding Data to a DataTable](../../framework/data/adonet/dataset-datatable-dataview/adding-data-to-a-datatable.md). diff --git a/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md index ae2b68cfd9812..5a61525e11265 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md @@ -28,7 +28,7 @@ Character sets include ignorable characters, which are characters that are not c ## Security considerations -If a security decision depends on a string comparison or a case change, you should use the property to ensure that the behavior is consistent, regardless of the culture settings of the operating system. +If a security decision depends on a string comparison or a case change, you should use the property to ensure that the behavior is consistent, regardless of the culture settings of the operating system. > [!NOTE] > When possible, you should use string comparison methods that have a parameter of type to specify the kind of comparison expected. As a general rule, use linguistic options (using the current culture) for comparing strings displayed in the user interface and specify or for security comparisons. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md index 654a22acbde9b..7cd86e108d691 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md @@ -46,9 +46,9 @@ An invariant culture is culture-insensitive. Your application specifies the inva A neutral culture is a culture that is associated with a language but not with a country/region. A specific culture is a culture that is associated with a language and a country/region. For example, `fr` is the neutral name for the French culture, and `fr-FR` is the name of the specific French (France) culture. Note that Chinese (Simplified) and Chinese (Traditional) are also considered neutral cultures. -Creating an instance of a class for a neutral culture is not recommended because the data it contains is arbitrary. To display and sort data, specify both the language and region. Additionally, the property of a object created for a neutral culture returns only the country and does not include the region. +Creating an instance of a class for a neutral culture is not recommended because the data it contains is arbitrary. To display and sort data, specify both the language and region. Additionally, the property of a object created for a neutral culture returns only the country and does not include the region. -The defined cultures have a hierarchy in which the parent of a specific culture is a neutral culture and the parent of a neutral culture is the invariant culture. The property contains the neutral culture associated with a specific culture. Custom cultures should define the property in conformance with this pattern. +The defined cultures have a hierarchy in which the parent of a specific culture is a neutral culture and the parent of a neutral culture is the invariant culture. The property contains the neutral culture associated with a specific culture. Custom cultures should define the property in conformance with this pattern. If the resources for a specific culture are not available in the operating system, the resources for the associated neutral culture are used. If the resources for the neutral culture are not available, the resources embedded in the main assembly are used. For more information on the resource fallback process, see [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps). @@ -184,7 +184,7 @@ As the output from the example shows, when the current culture is changed to Fre When a object is serialized, all that is actually stored is and . It is successfully deserialized only in an environment where that has the same meaning. The following three examples show why this is not always the case: -- If the property value is , and if that culture was first introduced in a particular version of the Windows operating system, it is not possible to deserialize it on an earlier version of Windows. For example, if a culture was introduced in Windows 10, it cannot be deserialized on Windows 8. +- If the property value is , and if that culture was first introduced in a particular version of the Windows operating system, it is not possible to deserialize it on an earlier version of Windows. For example, if a culture was introduced in Windows 10, it cannot be deserialized on Windows 8. - If the value is , and the computer on which it is deserialized does not have this user custom culture installed, it is not possible to deserialize it. @@ -194,7 +194,7 @@ When a object is serialized, all that is The user might choose to override some of the values associated with the current culture of Windows through the regional and language options portion of Control Panel. For example, the user might choose to display the date in a different format or to use a currency other than the default for the culture. In general, your applications should honor these user overrides. -If is `true` and the specified culture matches the current culture of Windows, the uses those overrides, including user settings for the properties of the instance returned by the property, and the properties of the instance returned by the property. If the user settings are incompatible with the culture associated with the , for example, if the selected calendar is not one of the , the results of the methods and the values of the properties are undefined. +If is `true` and the specified culture matches the current culture of Windows, the uses those overrides, including user settings for the properties of the instance returned by the property, and the properties of the instance returned by the property. If the user settings are incompatible with the culture associated with the , for example, if the selected calendar is not one of the , the results of the methods and the values of the properties are undefined. ## Alternate sort orders @@ -224,4 +224,4 @@ The following table lists the cultures that support alternate sort orders and th In Universal Windows Platform (UWP) apps, the and properties are read-write, just as they are in .NET Framework and .NET Core apps. However, UWP apps recognize a single culture. The and properties map to the first value in the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection. -In .NET apps, the current culture is a per-thread setting, and the and properties reflect the culture and UI culture of the current thread only. In UWP apps, the current culture maps to the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection, which is a global setting. Setting the or property changes the culture of the entire app; culture cannot be set on a per-thread basis. +In .NET apps, the current culture is a per-thread setting, and the and properties reflect the culture and UI culture of the current thread only. In UWP apps, the current culture maps to the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection, which is a global setting. Setting the or property changes the culture of the entire app; culture cannot be set on a per-thread basis. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md index 7053f620ed45c..268010501607d 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md @@ -25,9 +25,9 @@ A object can represent the format The invariant culture represents a culture that is culture-insensitive. It is based on the English language, but not on any specific English-speaking country/region. Although the data of specific cultures can be dynamic and can change to reflect new cultural conventions or user preferences, the data of the invariant culture does not change. You can instantiate a object that represents the formatting conventions of the invariant culture in the following ways: -- By retrieving the value of the property. The returned object is read-only. +- By retrieving the value of the property. The returned object is read-only. - By calling the parameterless constructor. The returned object is read/write. -- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. +- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. The following example uses each of these methods to instantiate a object that represents the invariant culture. It then indicates whether the object is read-only. @@ -65,9 +65,9 @@ You can use code like the following to determine which specific culture's format You can instantiate a object that represents the formatting conventions of the current culture in the following ways: -- By retrieving the value of the property. The returned object is read-only. +- By retrieving the value of the property. The returned object is read-only. -- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. +- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. - By calling the method with a object that represents the current culture. The returned object is read-only. @@ -77,11 +77,11 @@ The following example uses each of these methods to instantiate a object that represents the conventions of the current culture in one of these ways: -- By retrieving a object in any of the three previous ways and calling the method on the returned object. This creates a copy of the original object, except that its property is `false`. +- By retrieving a object in any of the three previous ways and calling the method on the returned object. This creates a copy of the original object, except that its property is `false`. - By calling the method to create a object that represents the current culture, and then using its property to retrieve the object. -The following example illustrates each way of instantiating a read/write object and displays the value of its property. +The following example illustrates each way of instantiating a read/write object and displays the value of its property. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate2.cs" id="Snippet7"::: @@ -97,9 +97,9 @@ The culture-specific data for formatting date and time values provided by the class can be used to replace the data of an existing culture. -- Cascading changes to property values. A number of culture-related properties can change at runtime, which, in turn, causes data to change. For example, the current culture can be changed either programmatically or through user action. When this happens, the object returned by the property changes to an object associated with the current culture. Similarly, a culture's calendar can change, which can result in changes to numerous property values. +- Cascading changes to property values. A number of culture-related properties can change at runtime, which, in turn, causes data to change. For example, the current culture can be changed either programmatically or through user action. When this happens, the object returned by the property changes to an object associated with the current culture. Similarly, a culture's calendar can change, which can result in changes to numerous property values. -- User preferences. Users of your application might choose to override some of the values associated with the current system culture through the regional and language options in Control Panel. For example, users might choose to display the date in a different format. If the property is set to `true`, the properties of the object is also retrieved from the user settings. If the user settings are incompatible with the culture associated with the object (for example, if the selected calendar is not one of the calendars indicated by the property), the results of the methods and the values of the properties are undefined. +- User preferences. Users of your application might choose to override some of the values associated with the current system culture through the regional and language options in Control Panel. For example, users might choose to display the date in a different format. If the property is set to `true`, the properties of the object is also retrieved from the user settings. If the user settings are incompatible with the culture associated with the object (for example, if the selected calendar is not one of the calendars indicated by the property), the results of the methods and the values of the properties are undefined. To minimize the possibility of inconsistent data, all user-overridable properties of a object are initialized when the object is created. There is still a possibility of inconsistency, because neither object creation nor the user override process is atomic and the relevant values can change during object creation. However, this situation should be extremely rare. @@ -139,7 +139,7 @@ The following example illustrates the relationship between the object includes three kinds of properties that are used in formatting operations with date and time values: -- Calendar-related properties. Properties such as , , , and , are associated with the calendar used by the culture, which is defined by the property. These properties are used for long date and time formats. +- Calendar-related properties. Properties such as , , , and , are associated with the calendar used by the culture, which is defined by the property. These properties are used for long date and time formats. - Properties that produce a standards-defined result string. The , , and properties contain custom format strings that produce result strings defined by international standards. These properties are read-only and cannot be modified. @@ -175,7 +175,7 @@ The [standard date and time format strings](../../standard/base-types/standard-d ## Modify DateTimeFormatInfo properties -You can change the result string produced by date and time format strings by modifying the associated properties of a writable object. To determine if a object is writable, use the property. To customize a object in this way: +You can change the result string produced by date and time format strings by modifying the associated properties of a writable object. To determine if a object is writable, use the property. To customize a object in this way: 1. Create a read/write copy of a object whose formatting conventions you want to modify. @@ -191,23 +191,23 @@ There are two other ways to change the format of a result string: ### Change the short date pattern -The following example changes the format of a result string produced by the "d" (short date) standard format string. It changes the associated property for the en-US or English (United States) culture from its default of "M/d/yyyy" to "yyyy'-"MM"-"dd" and uses the "d" standard format string to display the date both before and after the property is changed. +The following example changes the format of a result string produced by the "d" (short date) standard format string. It changes the associated property for the en-US or English (United States) culture from its default of "M/d/yyyy" to "yyyy'-"MM"-"dd" and uses the "d" standard format string to display the date both before and after the property is changed. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example1.cs" id="Snippet10"::: ### Change the date separator character -The following example changes the date separator character in a object that represents the formatting conventions of the fr-FR culture. The example uses the "g" standard format string to display the date both before and after the property is changed. +The following example changes the date separator character in a object that represents the formatting conventions of the fr-FR culture. The example uses the "g" standard format string to display the date both before and after the property is changed. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example3.cs" id="Snippet12"::: ### Change day name abbreviations and the long date pattern -In some cases, the long date pattern, which typically displays the full day and month name along with the number of the day of the month and the year, may be too long. The following example shortens the long date pattern for the en-US culture to return a one-character or two-character day name abbreviation followed by the day number, the month name abbreviation, and the year. It does this by assigning shorter day name abbreviations to the array, and by modifying the custom format string assigned to the property. This affects the result strings returned by the "D" and "f" standard format strings. +In some cases, the long date pattern, which typically displays the full day and month name along with the number of the day of the month and the year, may be too long. The following example shortens the long date pattern for the en-US culture to return a one-character or two-character day name abbreviation followed by the day number, the month name abbreviation, and the year. It does this by assigning shorter day name abbreviations to the array, and by modifying the custom format string assigned to the property. This affects the result strings returned by the "D" and "f" standard format strings. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example2.cs" id="Snippet13"::: -Ordinarily, the change to the property also affects the property, which in turn defines the result string returned by the "F" standard format string. To preserve the original full date and time pattern, the example reassigns the original custom format string assigned to the property after the property is modified. +Ordinarily, the change to the property also affects the property, which in turn defines the result string returned by the "F" standard format string. To preserve the original full date and time pattern, the example reassigns the original custom format string assigned to the property after the property is modified. ### Change from a 12-hour clock to a 24-hour clock @@ -228,15 +228,15 @@ The `nonHours` capturing group contains the minute and possibly the second compo ### Display and change the era in a date -The following example adds the "g" custom format specifier to the property of an object that represents the formatting conventions of the en-US culture. This addition affects the following three standard format strings: +The following example adds the "g" custom format specifier to the property of an object that represents the formatting conventions of the en-US culture. This addition affects the following three standard format strings: -- The "D" (long date) standard format string, which maps directly to the property. +- The "D" (long date) standard format string, which maps directly to the property. - The "f" (full date / short time) standard format string, which produces a result string that concatenates the substrings produced by the and properties. -- The "F" (full date / long time) standard format string, which maps directly to the property. Because we have not explicitly set this property value, it is generated dynamically by concatenating the and properties. +- The "F" (full date / long time) standard format string, which maps directly to the property. Because we have not explicitly set this property value, it is generated dynamically by concatenating the and properties. -The example also shows how to change the era name for a culture whose calendar has a single era. In this case, the en-US culture uses the Gregorian calendar, which is represented by a object. The class supports a single era, which it names A.D. (Anno Domini). The example changes the era name to C.E. (Common Era) by replacing the "g" custom format specifier in the format string assigned to the property with a literal string. The use of a literal string is necessary, because the era name is typically returned by the method from private data in the culture tables supplied by either .NET or the operating system. +The example also shows how to change the era name for a culture whose calendar has a single era. In this case, the en-US culture uses the Gregorian calendar, which is represented by a object. The class supports a single era, which it names A.D. (Anno Domini). The example changes the era name to C.E. (Common Era) by replacing the "g" custom format specifier in the format string assigned to the property with a literal string. The use of a literal string is necessary, because the era name is typically returned by the method from private data in the culture tables supplied by either .NET or the operating system. :::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example4.cs" id="Snippet11"::: @@ -269,7 +269,7 @@ The following example illustrates the difference between a parsing operation tha ### Serialize and deserialize date and time data -Serialized date and time data are expected to round-trip; that is, all serialized and deserialized values should be identical. If a date and time value represents a single moment in time, the deserialized value should represent the same moment in time regardless of the culture or time zone of the system on which it was restored. To round-trip date and time data successfully, you must use the conventions of the invariant culture, which is returned by the property, to generate and parse the data. The formatting and parsing operations should never reflect the conventions of the default culture. If you use default cultural settings, the portability of the data is strictly limited; it can be successfully deserialized only on a thread whose cultural-specific settings are identical to those of the thread on which it was serialized. In some cases, this means that the data cannot even be successfully serialized and deserialized on the same system. +Serialized date and time data are expected to round-trip; that is, all serialized and deserialized values should be identical. If a date and time value represents a single moment in time, the deserialized value should represent the same moment in time regardless of the culture or time zone of the system on which it was restored. To round-trip date and time data successfully, you must use the conventions of the invariant culture, which is returned by the property, to generate and parse the data. The formatting and parsing operations should never reflect the conventions of the default culture. If you use default cultural settings, the portability of the data is strictly limited; it can be successfully deserialized only on a thread whose cultural-specific settings are identical to those of the thread on which it was serialized. In some cases, this means that the data cannot even be successfully serialized and deserialized on the same system. If the time component of a date and time value is significant, it should also be converted to UTC and serialized by using the "o" or "r" [standard format string](../../standard/base-types/standard-date-and-time-format-strings.md). The time data can then be restored by calling a parsing method and passing it the appropriate format string along with the invariant culture as the `provider` argument. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md b/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md index 0c3301a90dca5..655c177067f0e 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md @@ -10,7 +10,7 @@ ms.topic: concept-article A culture-sensitive comparison of two strings depends on each character in the strings having several categories of sort weights, including script, alphabetic, case, and diacritic weights. A sort key serves as the repository of these weights for a particular string. -The method returns an instance of the class that reflects the culture-sensitive mapping of characters in a specified string. The value of a object is its key data, which is returned by the property. This key data consists of a series of bytes that encode the string, culture-specific sorting rules, and user-specified comparison options. A comparison using sort keys consists of a bitwise comparison of the corresponding key data in each sort key. For example, if you create a sort key by calling the method with a value of , a string comparison operation that uses the sort key is case-insensitive. +The method returns an instance of the class that reflects the culture-sensitive mapping of characters in a specified string. The value of a object is its key data, which is returned by the property. This key data consists of a series of bytes that encode the string, culture-specific sorting rules, and user-specified comparison options. A comparison using sort keys consists of a bitwise comparison of the corresponding key data in each sort key. For example, if you create a sort key by calling the method with a value of , a string comparison operation that uses the sort key is case-insensitive. After you create a sort key for a string, you compare sort keys by calling the static method. This method performs a simple byte-by-byte comparison, so it is much faster than the or method. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md b/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md index 2db021718dff9..91c21822c5299 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md @@ -38,11 +38,11 @@ You can instantiate a object in two ways - By calling the constructor, which instantiates a new object based on a version number and sort ID. This constructor is most useful when recreating a object from saved data. - By retrieving the value of the property. This property provides information about the Unicode version used by the .NET implementation on which the application is running. -The class has two properties, and , that indicate the Unicode version and the specific culture used for string comparison. The property is an arbitrary numeric value that reflects the Unicode version used for string comparison, and the property is an arbitrary that reflects the culture whose conventions are used for string comparison. The values of these two properties are important only when you compare two objects by using the method, the operator, or the operator. +The class has two properties, and , that indicate the Unicode version and the specific culture used for string comparison. The property is an arbitrary numeric value that reflects the Unicode version used for string comparison, and the property is an arbitrary that reflects the culture whose conventions are used for string comparison. The values of these two properties are important only when you compare two objects by using the method, the operator, or the operator. You typically use a object when saving or retrieving some form of culture-sensitive, ordered string data, such as indexes or the literal strings themselves. This requires the following steps: -1. When the ordered string data is saved, the and property values are also saved. +1. When the ordered string data is saved, the and property values are also saved. 2. When the ordered string data is retrieved, you can recreate the object used for ordering the strings by calling the constructor. diff --git a/docs/fundamentals/runtime-libraries/system-string.md b/docs/fundamentals/runtime-libraries/system-string.md index ee28def0c1f37..9eddefbf66676 100644 --- a/docs/fundamentals/runtime-libraries/system-string.md +++ b/docs/fundamentals/runtime-libraries/system-string.md @@ -102,7 +102,7 @@ Embedded null characters in a string are also treated differently when a string An index is the position of a object (not a Unicode character) in a . An index is a zero-based, nonnegative number that starts from the first position in the string, which is index position zero. A number of search methods, such as and , return the index of a character or substring in the string instance. -The property lets you access individual objects by their index position in the string. Because the property is the default property (in Visual Basic) or the indexer (in C# and F#), you can access the individual objects in a string by using code such as the following. This code looks for white space or punctuation characters in a string to determine how many words the string contains. +The property lets you access individual objects by their index position in the string. Because the property is the default property (in Visual Basic) or the indexer (in C# and F#), you can access the individual objects in a string by using code such as the following. This code looks for white space or punctuation characters in a string to determine how many words the string contains. :::code language="csharp" source="./snippets/System/String/Overview/csharp/index11.cs" id="Snippet4"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/index11.fs" id="Snippet4"::: diff --git a/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md b/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md index f4afc0aa8c58c..74f3c0ddc3527 100644 --- a/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md +++ b/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md @@ -110,9 +110,9 @@ You can use the methods of the class to iterate ### Iterate StringBuilder characters -You can access the characters in a object by using the property. In C#, is an indexer; in Visual Basic, it is the default property of the class. This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the property. Characters in a object begin at index 0 (zero) and continue to index - 1. +You can access the characters in a object by using the property. In C#, is an indexer; in Visual Basic, it is the default property of the class. This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the property. Characters in a object begin at index 0 (zero) and continue to index - 1. -The following example illustrates the property. It appends ten random numbers to a object, and then iterates each character. If the character's Unicode category is , it decreases the number by 1 (or changes the number to 9 if its value is 0). The example displays the contents of the object both before and after the values of individual characters were changed. +The following example illustrates the property. It appends ten random numbers to a object, and then iterates each character. If the character's Unicode category is , it decreases the number by 1 (or changes the number to 9 if its value is 0). The example displays the contents of the object both before and after the values of individual characters were changed. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/chars1.cs" id="Snippet7"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/chars1.fs" id="Snippet7"::: @@ -164,7 +164,7 @@ The class does not include methods similar to t |-----------|------|------| |Search string values before adding them to the object.|Useful for determining whether a substring exists.|Cannot be used when the index position of a substring is important.| |Call and search the returned object.|Easy to use if you assign all the text to a object, and then begin to modify it.|Cumbersome to repeatedly call if you must make modifications before all text is added to the object.

You must remember to work from the end of the object's text if you're making changes.| -|Use the property to sequentially search a range of characters.|Useful if you're concerned with individual characters or a small substring.|Cumbersome if the number of characters to search is large or if the search logic is complex.

Results in very poor performance for objects that have grown very large through repeated method calls. | +|Use the property to sequentially search a range of characters.|Useful if you're concerned with individual characters or a small substring.|Cumbersome if the number of characters to search is large or if the search logic is complex.

Results in very poor performance for objects that have grown very large through repeated method calls. | |Convert the object to a object, and perform modifications on the object.|Useful if the number of modifications is small.|Negates the performance benefit of the class if the number of modifications is large.| Let's examine these techniques in greater detail. @@ -188,7 +188,7 @@ Let's examine these techniques in greater detail. - Use the property to sequentially search a range of characters in a object. This approach might not be practical if the number of characters to be searched is large or the search logic is particularly complex. For the performance implications of character-by-character index-based access for very large, chunked objects, see the documentation for the property. - The following example is identical in functionality to the previous example but differs in implementation. It uses the property to detect when a character value has changed, inserts an underscore at that position, and converts the first character in the new sequence to uppercase. + The following example is identical in functionality to the previous example but differs in implementation. It uses the property to detect when a character value has changed, inserts an underscore at that position, and converts the first character in the new sequence to uppercase. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/pattern3.cs" id="Snippet14"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/pattern3.fs" id="Snippet14"::: diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md b/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md index 66f61574a3d78..39b588d30dc26 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md @@ -128,7 +128,7 @@ The class provides these methods and properties to r | method|Move to the first attribute in an element.| | method|Move to the next attribute in an element.| | method|Move to a specified attribute.| -| method or property|Get the value of a specified attribute.| +| method or property|Get the value of a specified attribute.| | property|Check whether the current node is an attribute that was generated from the default value defined in the DTD or schema.| | method|Move to the element that owns the current attribute. Use this method to return to an element after navigating through its attributes.| | method|Parse the attribute value into one or more `Text`, `EntityReference`, or `EndEntity` nodes.| @@ -151,7 +151,7 @@ When the XML reader is positioned on an XML declaration node, the method and property can be used to return the values for the SYSTEM and PUBLIC literals. For example, calling `reader.GetAttribute("PUBLIC")` returns the PUBLIC value. +When the XML reader is positioned on a document type node, the method and property can be used to return the values for the SYSTEM and PUBLIC literals. For example, calling `reader.GetAttribute("PUBLIC")` returns the PUBLIC value. **Reading attributes on processing instruction nodes** From d53ae1ce0dce72d940272387aad97c75256b7988 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 9 Feb 2026 17:22:04 -0800 Subject: [PATCH 4/7] undo file --- docs/fundamentals/runtime-libraries/includes/context.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/fundamentals/runtime-libraries/includes/context.md b/docs/fundamentals/runtime-libraries/includes/context.md index 48e7573b5ca2e..89814007b303e 100644 --- a/docs/fundamentals/runtime-libraries/includes/context.md +++ b/docs/fundamentals/runtime-libraries/includes/context.md @@ -1,2 +1 @@ -> [!NOTE] -> This article provides supplementary remarks to the reference documentation for this API. +This article provides supplementary remarks to the reference documentation for this API. From 69d4ee3c6899223a43bd277f283e05af8f524e71 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 9 Feb 2026 18:03:32 -0800 Subject: [PATCH 5/7] fix xrefs --- .../runtime-libraries/includes/stringbuilder-perf-note.md | 4 ++-- .../system-collections-generic-list{t}.md | 2 +- docs/fundamentals/runtime-libraries/system-string.md | 2 +- .../runtime-libraries/system-text-stringbuilder.md | 8 ++++---- .../runtime-libraries/system-xml-xmlreader.md | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md b/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md index 7490f241b3716..5357762c63fcb 100644 --- a/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md +++ b/docs/fundamentals/runtime-libraries/includes/stringbuilder-perf-note.md @@ -1,4 +1,4 @@ -Using character-based indexing with the property can be extremely slow under the following conditions: +Using character-based indexing with the property can be extremely slow under the following conditions: - The instance is large (for example, it consists of several tens of thousands of characters). - The is "chunky." That is, repeated calls to methods such as have automatically expanded the object's property and allocated new chunks of memory to it. @@ -6,7 +6,7 @@ Using character-based indexing with the p Performance is severely impacted because each character access walks the entire linked list of chunks to find the correct buffer to index into. > [!NOTE] -> Even for a large "chunky" object, using the property for index-based access to one or a small number of characters has a negligible performance impact; typically, it is an **O(n)** operation. The significant performance impact occurs when iterating the characters in the object, which is an **O(n^2)** operation. +> Even for a large "chunky" object, using the property for index-based access to one or a small number of characters has a negligible performance impact; typically, it is an **O(n)** operation. The significant performance impact occurs when iterating the characters in the object, which is an **O(n^2)** operation. If you encounter performance issues when using character-based indexing with objects, you can use any of the following workarounds: diff --git a/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md b/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md index d0c859a17ff4d..b22b5ea598cfa 100644 --- a/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md +++ b/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md @@ -59,7 +59,7 @@ The parameterless constructor is used to create a list of strings with the defau The method is used to test for the presence of an item in the list, the method is used to insert a new item in the middle of the list, and the contents of the list are displayed again. -The default property (the indexer in C#) is used to retrieve an item, the method is used to remove the first instance of the duplicate item added earlier, and the contents are displayed again. The method always removes the first instance it encounters. +The default property (the indexer in C#) is used to retrieve an item, the method is used to remove the first instance of the duplicate item added earlier, and the contents are displayed again. The method always removes the first instance it encounters. The method is used to reduce the capacity to match the count, and the and properties are displayed. If the unused capacity had been less than 10 percent of total capacity, the list would not have been resized. diff --git a/docs/fundamentals/runtime-libraries/system-string.md b/docs/fundamentals/runtime-libraries/system-string.md index 9eddefbf66676..0b8453b3c3cea 100644 --- a/docs/fundamentals/runtime-libraries/system-string.md +++ b/docs/fundamentals/runtime-libraries/system-string.md @@ -102,7 +102,7 @@ Embedded null characters in a string are also treated differently when a string An index is the position of a object (not a Unicode character) in a . An index is a zero-based, nonnegative number that starts from the first position in the string, which is index position zero. A number of search methods, such as and , return the index of a character or substring in the string instance. -The property lets you access individual objects by their index position in the string. Because the property is the default property (in Visual Basic) or the indexer (in C# and F#), you can access the individual objects in a string by using code such as the following. This code looks for white space or punctuation characters in a string to determine how many words the string contains. +The property lets you access individual objects by their index position in the string. Because the property is the default property (in Visual Basic) or the indexer (in C# and F#), you can access the individual objects in a string by using code such as the following. This code looks for white space or punctuation characters in a string to determine how many words the string contains. :::code language="csharp" source="./snippets/System/String/Overview/csharp/index11.cs" id="Snippet4"::: :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/index11.fs" id="Snippet4"::: diff --git a/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md b/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md index 74f3c0ddc3527..3506acc6b8fb7 100644 --- a/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md +++ b/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md @@ -110,9 +110,9 @@ You can use the methods of the class to iterate ### Iterate StringBuilder characters -You can access the characters in a object by using the property. In C#, is an indexer; in Visual Basic, it is the default property of the class. This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the property. Characters in a object begin at index 0 (zero) and continue to index - 1. +You can access the characters in a object by using the property. In C#, is an indexer; in Visual Basic, it is the default property of the class. This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the property. Characters in a object begin at index 0 (zero) and continue to index - 1. -The following example illustrates the property. It appends ten random numbers to a object, and then iterates each character. If the character's Unicode category is , it decreases the number by 1 (or changes the number to 9 if its value is 0). The example displays the contents of the object both before and after the values of individual characters were changed. +The following example illustrates the property. It appends ten random numbers to a object, and then iterates each character. If the character's Unicode category is , it decreases the number by 1 (or changes the number to 9 if its value is 0). The example displays the contents of the object both before and after the values of individual characters were changed. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/chars1.cs" id="Snippet7"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/chars1.fs" id="Snippet7"::: @@ -164,7 +164,7 @@ The class does not include methods similar to t |-----------|------|------| |Search string values before adding them to the object.|Useful for determining whether a substring exists.|Cannot be used when the index position of a substring is important.| |Call and search the returned object.|Easy to use if you assign all the text to a object, and then begin to modify it.|Cumbersome to repeatedly call if you must make modifications before all text is added to the object.

You must remember to work from the end of the object's text if you're making changes.| -|Use the property to sequentially search a range of characters.|Useful if you're concerned with individual characters or a small substring.|Cumbersome if the number of characters to search is large or if the search logic is complex.

Results in very poor performance for objects that have grown very large through repeated method calls. | +|Use the property to sequentially search a range of characters.|Useful if you're concerned with individual characters or a small substring.|Cumbersome if the number of characters to search is large or if the search logic is complex.

Results in very poor performance for objects that have grown very large through repeated method calls. | |Convert the object to a object, and perform modifications on the object.|Useful if the number of modifications is small.|Negates the performance benefit of the class if the number of modifications is large.| Let's examine these techniques in greater detail. @@ -188,7 +188,7 @@ Let's examine these techniques in greater detail. - Use the property to sequentially search a range of characters in a object. This approach might not be practical if the number of characters to be searched is large or the search logic is particularly complex. For the performance implications of character-by-character index-based access for very large, chunked objects, see the documentation for the property. - The following example is identical in functionality to the previous example but differs in implementation. It uses the property to detect when a character value has changed, inserts an underscore at that position, and converts the first character in the new sequence to uppercase. + The following example is identical in functionality to the previous example but differs in implementation. It uses the property to detect when a character value has changed, inserts an underscore at that position, and converts the first character in the new sequence to uppercase. :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/pattern3.cs" id="Snippet14"::: :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/pattern3.fs" id="Snippet14"::: diff --git a/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md b/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md index 39b588d30dc26..69a7a9ed800fd 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md +++ b/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md @@ -128,7 +128,7 @@ The class provides these methods and properties to r | method|Move to the first attribute in an element.| | method|Move to the next attribute in an element.| | method|Move to a specified attribute.| -| method or property|Get the value of a specified attribute.| +| method or property|Get the value of a specified attribute.| | property|Check whether the current node is an attribute that was generated from the default value defined in the DTD or schema.| | method|Move to the element that owns the current attribute. Use this method to return to an element after navigating through its attributes.| | method|Parse the attribute value into one or more `Text`, `EntityReference`, or `EndEntity` nodes.| @@ -151,7 +151,7 @@ When the XML reader is positioned on an XML declaration node, the method and property can be used to return the values for the SYSTEM and PUBLIC literals. For example, calling `reader.GetAttribute("PUBLIC")` returns the PUBLIC value. +When the XML reader is positioned on a document type node, the method and property can be used to return the values for the SYSTEM and PUBLIC literals. For example, calling `reader.GetAttribute("PUBLIC")` returns the PUBLIC value. **Reading attributes on processing instruction nodes** From 2913cd6a1fe10257698853e5fdfe42d5c8c173c1 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 9 Feb 2026 18:04:03 -0800 Subject: [PATCH 6/7] don't add these files yet --- ...ction-emit-dynamicmethod-createdelegate.md | 53 ------------ ...stem-reflection-emit-dynamicmethod-ctor.md | 81 ------------------- ...tion-emit-dynamicmethod-defineparameter.md | 20 ----- ...ction-emit-dynamicmethod-getilgenerator.md | 37 --------- ...em-reflection-emit-dynamicmethod-invoke.md | 31 ------- ...n-emit-dynamicmethod-issecuritycritical.md | 41 ---------- ...it-dynamicmethod-issecuritysafecritical.md | 41 ---------- ...mit-dynamicmethod-issecuritytransparent.md | 41 ---------- ...stem-reflection-emit-dynamicmethod-name.md | 19 ----- 9 files changed, 364 deletions(-) delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-defineparameter.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritysafecritical.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritytransparent.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-name.md diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md deleted file mode 100644 index 73b97a9bb51db..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.CreateDelegate methods -description: Learn about the System.Reflection.Emit.DynamicMethod.CreateDelegate methods. -ms.date: 02/10/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Emit.DynamicMethod.CreateDelegate methods - -[!INCLUDE [context](includes/context.md)] - -## - -Calling the method or the method completes the dynamic method. Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown. - -To create a method body for a dynamic method when you have your own MSIL generator, call the method to obtain a object. If you don't have your own MSIL generator, call the method to obtain an object that can be used to generate the method body. - -### Examples - -The following code example creates a dynamic method that takes two parameters. The example emits a simple function body that prints the first parameter to the console, and the example uses the second parameter as the return value of the method. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the method. - -:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/.ctor/source1.cs" id="Snippet1"::: -:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/.ctor/source1.vb" id="Snippet1"::: - -## - -This method overload creates a delegate bound to a particular object. Such a delegate is said to be closed over its first argument. Although the method is static, it acts as if it were an instance method; the instance is `target`. - -This method overload requires `target` to be of the same type as the first parameter of the dynamic method, or to be assignable to that type (for example, a derived class). The signature of `delegateType` has all the parameters of the dynamic method except the first. For example, if the dynamic method has the parameters , , and , then `delegateType` has the parameters and ; `target` is of type . - -Calling the method or the method completes the dynamic method. Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown. - -To create a method body for a dynamic method when you have your own MSIL generator, call the method to obtain a object. If you don't have your own MSIL generator, call the method to obtain an object that can be used to generate the method body. - -### Examples - -The following code example creates a delegate that binds a to an instance of a type, so that the method acts on the same instance each time it's invoked. - -The code example defines a class named `Example` with a private field, a class named `DerivedFromExample` that derives from the first class, a delegate type named `UseLikeStatic` that returns and has parameters of type `Example` and , and a delegate type named `UseLikeInstance` that returns and has one parameter of type . - -The example code then creates a that changes the private field of an instance of `Example` and returns the previous value. - -> [!NOTE] -> In general, changing the internal fields of classes isn't good object-oriented coding practice. - -The example code creates an instance of `Example` and then creates two delegates. The first is of type `UseLikeStatic`, which has the same parameters as the dynamic method. The second is of type `UseLikeInstance`, which lacks the first parameter (of type `Example`). This delegate is created using the method overload; the second parameter of that method overload is an instance of `Example`, in this case the instance just created, which is bound to the newly created delegate. Whenever that delegate is invoked, the dynamic method acts on the bound instance of `Example`. - -> [!NOTE] -> This is an example of the relaxed rules for delegate binding introduced in .NET Framework 2.0, along with new overloads of the method. For more information, see the class. - -The `UseLikeStatic` delegate is invoked, passing in the instance of `Example` that's bound to the `UseLikeInstance` delegate. Then the `UseLikeInstance` delegate is invoked, so that both delegates act on the same instance of `Example`. The changes in the values of the internal field are displayed after each call. Finally, a `UseLikeInstance` delegate is bound to an instance of `DerivedFromExample`, and the delegate calls are repeated. - -:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/.ctor/source.cs" id="Snippet1"::: -:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/.ctor/source.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md deleted file mode 100644 index 52d4369258275..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod constructors -description: Learn about the System.Reflection.Emit.DynamicMethod constructors. -ms.date: 02/10/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Emit.DynamicMethod constructors - -[!INCLUDE [context](includes/context.md)] - -## constructor - -The dynamic method that is created by this constructor is associated with an anonymous assembly instead of an existing type or module. The anonymous assembly exists only to provide a sandbox environment for dynamic methods, that is, to isolate them from other code. This environment makes it safe for the dynamic method to be emitted and executed by partially trusted code. - -Anonymously hosted dynamic methods don't have automatic access to any types or members that are `private`, `protected`, or `internal` (`Friend` in Visual Basic). This is different from dynamic methods that are associated with an existing type or module, which have access to hidden members in their associated scope. - -Specify `true` for `restrictedSkipVisibility` if your dynamic method has to access types or members that are `private`, `protected`, or `internal`. This gives the dynamic method restricted access to these members. That is, the members can be accessed only if the following conditions are met: - -- The target members belong to an assembly that has a level of trust equal to or lower than the call stack that emits the dynamic method. - -- The call stack that emits the dynamic method is granted with the flag. This is always true when the code is executed with full trust. For partially trusted code, it's true only if the host explicitly grants the permission. - - > [!IMPORTANT] - > If the permission hasn't been granted, a security exception is thrown when is called or when the dynamic method is invoked, not when this constructor is called. No special permissions are required to emit the dynamic method. - -For example, a dynamic method that's created with `restrictedSkipVisibility` set to `true` can access a private member of any assembly on the call stack if the call stack has been granted restricted member access. If the dynamic method is created with partially trusted code on the call stack, it can't access a private member of a type in a .NET Framework assembly, because such assemblies are fully trusted. - -If `restrictedSkipVisibility` is `false`, JIT visibility checks are enforced. The code in the dynamic method has access to public methods of public classes, and exceptions are thrown if it tries to access types or members that are `private`, `protected`, or `internal`. - -When an anonymously hosted dynamic method is constructed, the call stack of the emitting assembly is included. When the method is invoked, the permissions of the emitting call stack are used instead of the permissions of the actual caller. Thus, the dynamic method can't execute at a higher level of privilege than that of the assembly that emitted it, even if it's passed to and executed by an assembly that has a higher trust level. - -This constructor specifies the method attributes and , and the calling convention . - -> [!NOTE] -> This constructor was introduced in .NET Framework 3.5 or later. - -## constructor - -This constructor specifies method attributes and , calling convention , and doesn't skip just-in-time (JIT) visibility checks. - -The dynamic method created with this constructor has access to public and `internal` (`Friend` in Visual Basic) members of all the types contained in module `m`. - -> [!NOTE] -> For backward compatibility, this constructor demands with the flag if the following conditions are both true: `m` is a module other than the calling module, and the demand for with the flag has failed. If the demand for succeeds, the operation is allowed. - -### Examples - -The following code example creates a dynamic method that takes two parameters. The example emits a simple function body that prints the first parameter to the console, and the example uses the second parameter as the return value of the method. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the method. - -:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/.ctor/source1.cs" id="Snippet1"::: -:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/.ctor/source1.vb" id="Snippet1"::: - -## constructor - -The dynamic method created with this constructor has access to all members of the type `owner`, and to public and `internal` (`Friend` in Visual Basic) members of all the other types in the module that contains `owner`. - -This constructor specifies method attributes and , calling convention , and doesn't skip just-in-time (JIT) visibility checks. - -> [!NOTE] -> For backward compatibility, this constructor demands with the flag if the following conditions are both true: `owner` is in a module other than the calling module, and the demand for with the flag has failed. If the demand for succeeds, the operation is allowed. - -### Examples - -The following code example creates a that's logically associated with a type. This association gives it access to the private members of that type. - -The code example defines a class named `Example` with a private field, a class named `DerivedFromExample` that derives from the first class, a delegate type named `UseLikeStatic` that returns and has parameters of type `Example` and , and a delegate type named `UseLikeInstance` that returns and has one parameter of type . - -The example code then creates a that changes the private field of an instance of `Example` and returns the previous value. - -> [!NOTE] -> In general, changing the internal fields of classes isn't good object-oriented coding practice. - -The example code creates an instance of `Example` and then creates two delegates. The first is of type `UseLikeStatic`, which has the same parameters as the dynamic method. The second is of type `UseLikeInstance`, which lacks the first parameter (of type `Example`). This delegate is created using the method overload; the second parameter of that method overload is an instance of `Example`, in this case the instance just created, which is bound to the newly created delegate. Whenever that delegate is invoked, the dynamic method acts on the bound instance of `Example`. - -> [!NOTE] -> This is an example of the relaxed rules for delegate binding introduced in .NET Framework 2.0, along with new overloads of the method. For more information, see the class. - -The `UseLikeStatic` delegate is invoked, passing in the instance of `Example` that's bound to the `UseLikeInstance` delegate. Then the `UseLikeInstance` delegate is invoked, so that both delegates act on the same instance of `Example`. The changes in the values of the internal field are displayed after each call. Finally, a `UseLikeInstance` delegate is bound to an instance of `DerivedFromExample`, and the delegate calls are repeated. - -:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/.ctor/source.cs" id="Snippet1"::: -:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/.ctor/source.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-defineparameter.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-defineparameter.md deleted file mode 100644 index aa615217e02a8..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-defineparameter.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.DefineParameter method -description: Learn about the System.Reflection.Emit.DynamicMethod.DefineParameter method. -ms.date: 02/10/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Emit.DynamicMethod.DefineParameter method - -[!INCLUDE [context](includes/context.md)] - -If `position` is 0, the method refers to the return value. Setting parameter information has no effect on the return value. - -If the dynamic method has already been completed, by calling the or method, the method has no effect. No exception is thrown. - -## Examples - -The following code example shows how to define parameter information for a dynamic method. This code example is part of a larger example provided for the class. - -:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/Overview/source.cs" id="Snippet33"::: -:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/Overview/source.vb" id="Snippet33"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md deleted file mode 100644 index cd3f38a6b613e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.GetILGenerator methods -description: Learn about the System.Reflection.Emit.DynamicMethod.GetILGenerator methods. -ms.date: 02/10/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Emit.DynamicMethod.GetILGenerator methods - -[!INCLUDE [context](includes/context.md)] - -## - -After a dynamic method has been completed, by calling the or method, any further attempt to add MSIL is ignored. No exception is thrown. - -> [!NOTE] -> There are restrictions on unverifiable code in dynamic methods, even in some full-trust scenarios. See the "Verification" section in Remarks for . - -### Examples - -The following code example creates a dynamic method that takes two parameters. The example emits a simple function body that prints the first parameter to the console, and the example uses the second parameter as the return value of the method. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the method. - -:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/.ctor/source1.cs" id="Snippet1"::: -:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/.ctor/source1.vb" id="Snippet1"::: - -## - -After a dynamic method has been completed, by calling the or method, any further attempt to add MSIL is ignored. No exception is thrown. - -> [!NOTE] -> There are restrictions on unverifiable code in dynamic methods, even in some full-trust scenarios. See the "Verification" section in Remarks for . - -### Examples - -The following code example demonstrates this method overload. This code example is part of a larger example provided for the class. - -:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/Overview/source.cs" id="Snippet2"::: -:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/Overview/source.vb" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md deleted file mode 100644 index 9202c64d1c51a..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.Invoke method -description: Learn about the System.Reflection.Emit.DynamicMethod.Invoke method. -ms.date: 02/10/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Emit.DynamicMethod.Invoke method - -[!INCLUDE [context](includes/context.md)] - -In addition to the listed exceptions, the calling code should be prepared to catch any exceptions thrown by the dynamic method. - -Executing a dynamic method with a delegate created by the method is more efficient than executing it with the method. - -Calling the method or the method completes the dynamic method. Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown. - -All dynamic methods are static, so the `obj` parameter is always ignored. To treat a dynamic method as if it were an instance method, use the overload that takes an object instance. - -If the dynamic method has no parameters, the value of `parameters` should be `null`. Otherwise the number, type, and order of elements in the parameters array should be identical to the number, type, and order of parameters of the dynamic method. - -> [!NOTE] -> This method overload is called by the method overload inherited from the class, so the preceding remarks apply to both overloads. - -This method doesn't demand permissions directly, but invoking the dynamic method can result in security demands, depending on the method. For example, no demands are made for anonymously hosted dynamic methods that are created with the `restrictedSkipVisibility` parameter set to `false`. On the other hand, if you create a method with `restrictedSkipVisibility` set to `true` so it can access a hidden member of a target assembly, the method causes a demand for the permissions of the target assembly plus with the flag. - -## Examples - -The following code example invokes a dynamic method with exact binding, using the US-English culture. This code example is part of a larger example provided for the class. - -:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/Overview/source.cs" id="Snippet4"::: -:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/Overview/source.vb" id="Snippet4"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md deleted file mode 100644 index 6bae05b6ff73d..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.IsSecurityCritical property -description: Learn about the System.Reflection.Emit.DynamicMethod.IsSecurityCritical property. -ms.date: 02/10/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Emit.DynamicMethod.IsSecurityCritical property - -[!INCLUDE [context](includes/context.md)] - -The , , and properties report the transparency level of the dynamic method as determined by the common language runtime (CLR). The combinations of these properties are shown in the following table: - -| Security level | IsSecurityCritical | IsSecuritySafeCritical | IsSecurityTransparent | -|----------------|--------------------|-----------------------|-----------------------| -| Critical | `true` | `false` | `false` | -| Safe critical | `true` | `true` | `false` | -| Transparent | `false` | `false` | `true` | - -Using these properties is much simpler than examining the security annotations of an assembly and its types, checking the current trust level, and attempting to duplicate the runtime's rules. - -The transparency of a dynamic method depends on the module it's associated with. If the dynamic method is associated with a type rather than a module, its transparency depends on the module that contains the type. Dynamic methods don't have security annotations, so they're assigned the default transparency for the associated module. - -- Anonymously hosted dynamic methods are always transparent, because the system-provided module that contains them is transparent. - -- The transparency of a dynamic method that's associated with a trusted assembly (that is, a strong-named assembly that's installed in the global assembly cache) is described in the following table. - - | Assembly annotation | Level 1 transparency | Level 2 transparency | - |---------------------|----------------------|----------------------| - | Fully transparent | Transparent | Transparent | - | Fully critical | Critical | Critical | - | Mixed transparency | Transparent | Transparent | - | Security-agnostic | Safe-critical | Critical | - - For example, if you associate a dynamic method with a type that's in mscorlib.dll, which has level 2 mixed transparency, the dynamic method is transparent and can't execute critical code. For information about transparency levels, see [Security-Transparent Code, Level 1](/dotnet/framework/misc/security-transparent-code-level-1) and [Security-Transparent Code, Level 2](/dotnet/framework/misc/security-transparent-code-level-2). - - > [!NOTE] - > Associating a dynamic method with a module in a trusted level 1 assembly that's security-agnostic, such as System.dll, doesn't permit elevation of trust. If the grant set of the code that calls the dynamic method doesn't include the grant set of System.dll (that is, full trust), is thrown when the dynamic method is called. - -- The transparency of a dynamic method that's associated with a partially trusted assembly depends on how the assembly is loaded. If the assembly is loaded with partial trust (for example, into a sandboxed application domain), the runtime ignores the security annotations of the assembly. The assembly and all its types and members, including dynamic methods, are treated as transparent. The runtime pays attention to security annotations only if the partial-trust assembly is loaded with full trust (for example, into the default application domain of a desktop application). In that case, the runtime assigns the dynamic method the default transparency for methods according to the assembly's annotations. - -For more information about reflection emit and transparency, see [Security Issues in Reflection Emit](/dotnet/framework/reflection-and-codedom/security-issues-in-reflection-emit). For information about transparency, see [Security Changes](/dotnet/framework/security/security-changes). diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritysafecritical.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritysafecritical.md deleted file mode 100644 index 31e9004707e43..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritysafecritical.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.IsSecuritySafeCritical property -description: Learn about the System.Reflection.Emit.DynamicMethod.IsSecuritySafeCritical property. -ms.date: 02/10/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Emit.DynamicMethod.IsSecuritySafeCritical property - -[!INCLUDE [context](includes/context.md)] - -The , , and properties report the transparency level of the dynamic method as determined by the common language runtime (CLR). The combinations of these properties are shown in the following table: - -| Security level | IsSecurityCritical | IsSecuritySafeCritical | IsSecurityTransparent | -|----------------|--------------------|-----------------------|-----------------------| -| Critical | `true` | `false` | `false` | -| Safe critical | `true` | `true` | `false` | -| Transparent | `false` | `false` | `true` | - -Using these properties is much simpler than examining the security annotations of an assembly and its types, checking the current trust level, and attempting to duplicate the runtime's rules. - -The transparency of a dynamic method depends on the module it's associated with. If the dynamic method is associated with a type rather than a module, its transparency depends on the module that contains the type. Dynamic methods don't have security annotations, so they're assigned the default transparency for the associated module. - -- Anonymously hosted dynamic methods are always transparent, because the system-provided module that contains them is transparent. - -- The transparency of a dynamic method that's associated with a trusted assembly (that is, a strong-named assembly that's installed in the global assembly cache) is described in the following table. - - | Assembly annotation | Level 1 transparency | Level 2 transparency | - |---------------------|----------------------|----------------------| - | Fully transparent | Transparent | Transparent | - | Fully critical | Critical | Critical | - | Mixed transparency | Transparent | Transparent | - | Security-agnostic | Safe-critical | Critical | - - For example, if you associate a dynamic method with a type that's in mscorlib.dll, which has level 2 mixed transparency, the dynamic method is transparent and can't execute critical code. For information about transparency levels, see [Security-Transparent Code, Level 1](/dotnet/framework/misc/security-transparent-code-level-1) and [Security-Transparent Code, Level 2](/dotnet/framework/misc/security-transparent-code-level-2). - - > [!NOTE] - > Associating a dynamic method with a module in a trusted level 1 assembly that's security-agnostic, such as System.dll, doesn't permit elevation of trust. If the grant set of the code that calls the dynamic method doesn't include the grant set of System.dll (that is, full trust), is thrown when the dynamic method is called. - -- The transparency of a dynamic method that's associated with a partially trusted assembly depends on how the assembly is loaded. If the assembly is loaded with partial trust (for example, into a sandboxed application domain), the runtime ignores the security annotations of the assembly. The assembly and all its types and members, including dynamic methods, are treated as transparent. The runtime pays attention to security annotations only if the partial-trust assembly is loaded with full trust (for example, into the default application domain of a desktop application). In that case, the runtime assigns the dynamic method the default transparency for methods according to the assembly's annotations. - -For more information about reflection emit and transparency, see [Security Issues in Reflection Emit](/dotnet/framework/reflection-and-codedom/security-issues-in-reflection-emit). For information about transparency, see [Security Changes](/dotnet/framework/security/security-changes). diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritytransparent.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritytransparent.md deleted file mode 100644 index cf20060f09d53..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritytransparent.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.IsSecurityTransparent property -description: Learn about the System.Reflection.Emit.DynamicMethod.IsSecurityTransparent property. -ms.date: 02/10/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Emit.DynamicMethod.IsSecurityTransparent property - -[!INCLUDE [context](includes/context.md)] - -The , , and properties report the transparency level of the dynamic method as determined by the common language runtime (CLR). The combinations of these properties are shown in the following table: - -| Security level | IsSecurityCritical | IsSecuritySafeCritical | IsSecurityTransparent | -|----------------|--------------------|-----------------------|-----------------------| -| Critical | `true` | `false` | `false` | -| Safe critical | `true` | `true` | `false` | -| Transparent | `false` | `false` | `true` | - -Using these properties is much simpler than examining the security annotations of an assembly and its types, checking the current trust level, and attempting to duplicate the runtime's rules. - -The transparency of a dynamic method depends on the module it's associated with. If the dynamic method is associated with a type rather than a module, its transparency depends on the module that contains the type. Dynamic methods don't have security annotations, so they're assigned the default transparency for the associated module. - -- Anonymously hosted dynamic methods are always transparent, because the system-provided module that contains them is transparent. - -- The transparency of a dynamic method that's associated with a trusted assembly (that is, a strong-named assembly that's installed in the global assembly cache) is described in the following table. - - | Assembly annotation | Level 1 transparency | Level 2 transparency | - |---------------------|----------------------|----------------------| - | Fully transparent | Transparent | Transparent | - | Fully critical | Critical | Critical | - | Mixed transparency | Transparent | Transparent | - | Security-agnostic | Safe-critical | Critical | - - For example, if you associate a dynamic method with a type that's in mscorlib.dll, which has level 2 mixed transparency, the dynamic method is transparent and can't execute critical code. For information about transparency levels, see [Security-Transparent Code, Level 1](/dotnet/framework/misc/security-transparent-code-level-1) and [Security-Transparent Code, Level 2](/dotnet/framework/misc/security-transparent-code-level-2). - - > [!NOTE] - > Associating a dynamic method with a module in a trusted level 1 assembly that's security-agnostic, such as System.dll, doesn't permit elevation of trust. If the grant set of the code that calls the dynamic method doesn't include the grant set of System.dll (that is, full trust), is thrown when the dynamic method is called. - -- The transparency of a dynamic method that's associated with a partially trusted assembly depends on how the assembly is loaded. If the assembly is loaded with partial trust (for example, into a sandboxed application domain), the runtime ignores the security annotations of the assembly. The assembly and all its types and members, including dynamic methods, are treated as transparent. The runtime pays attention to security annotations only if the partial-trust assembly is loaded with full trust (for example, into the default application domain of a desktop application). In that case, the runtime assigns the dynamic method the default transparency for methods according to the assembly's annotations. - -For more information about reflection emit and transparency, see [Security Issues in Reflection Emit](/dotnet/framework/reflection-and-codedom/security-issues-in-reflection-emit). For information about transparency, see [Security Changes](/dotnet/framework/security/security-changes). diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-name.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-name.md deleted file mode 100644 index 9846db7c93c33..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-name.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.Name property -description: Learn about the System.Reflection.Emit.DynamicMethod.Name property. -ms.date: 02/10/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Emit.DynamicMethod.Name property - -[!INCLUDE [context](includes/context.md)] - -> [!NOTE] -> It's not necessary to name dynamic methods. - -## Examples - -The following code example displays the name of a dynamic method. This code example is part of a larger example provided for the class. - -:::code language="csharp" source="~/snippets/csharp/System.Reflection.Emit/DynamicMethod/Overview/source.cs" id="Snippet27"::: -:::code language="vb" source="~/snippets/visualbasic/System.Reflection.Emit/DynamicMethod/Overview/source.vb" id="Snippet27"::: From 3449dd1b7c5bdedbbcad03fa417cff895175257d Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 9 Feb 2026 18:22:06 -0800 Subject: [PATCH 7/7] Apply suggestions from code review Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- ...ons-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md | 2 +- docs/fundamentals/runtime-libraries/system-double-equals.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md b/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md index 60f9675347ea5..bfed7c07babe6 100644 --- a/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md +++ b/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md @@ -7,7 +7,7 @@ ms.date: 01/24/2024 [!INCLUDE [context](includes/context.md)] -The method does not modify the key embedded in `item`; it simply replaces the key saved in the lookup dictionary. Therefore, if `newKey` is different from the key that is embedded in `item`, you cannot access `item` by using the key returned by . +The method does not modify the key embedded in `item`; it simply replaces the key saved in the lookup dictionary. Therefore, if `newKey` is different from the key that is embedded in `item`, you cannot access `item` by using the key returned by . This method does nothing if the does not have a lookup dictionary. diff --git a/docs/fundamentals/runtime-libraries/system-double-equals.md b/docs/fundamentals/runtime-libraries/system-double-equals.md index 40e6ecbcdc9d1..9a277a3196598 100644 --- a/docs/fundamentals/runtime-libraries/system-double-equals.md +++ b/docs/fundamentals/runtime-libraries/system-double-equals.md @@ -9,7 +9,7 @@ dev_langs: --- # System.Double.Equals method -Th method implements the interface, and performs slightly better than because it doesn't have to convert the `obj` parameter to an object. +The method implements the interface, and performs slightly better than because it doesn't have to convert the `obj` parameter to an object. ## Widening conversions