Do not pass types by reference
Do not pass types by reference
Microsoft docsDescription
Passing types by reference (using out or ref) requires experience with pointers, understanding how value types and reference types differ, and handling methods that have multiple return values. Also, the difference between out and ref parameters is not widely understood.
When a reference type is passed "by reference," the method intends to use the parameter to return a different instance of the object. (Passing a reference type by reference is also known as using a double pointer, pointer to a pointer, or double indirection.) Using the default calling convention, which is pass "by value," a parameter that takes a reference type already receives a pointer to the object. The pointer, not the object to which it points, is passed by value. Passing by value means that the method cannot change the pointer to have it point to a new instance of the reference type, but can change the contents of the object to which it points. For most applications this is sufficient and yields the behavior that you want.
If a method must return a different instance, use the return value of the method to accomplish this. For methods that operate on strings and return a new instance of a string, see the System.String class. By using this model, it is left to the caller to decide whether the original object is preserved.
Although return values are commonplace and heavily used, the correct application of out and ref parameters requires intermediate design and coding skills. Library architects who design for a general audience should not expect users to become proficient in working with out or ref parameters. When you work with parameters that are large structures, the additional resources that are required to copy these structures could have a performance effect when you pass by value. In these cases, you might consider using ref or out parameters.
Cause
A public or protected method in a public type has a ref parameter that takes a primitive type, a reference type, or a value type that is not one of the built-in types.
How to fix violations
To fix a violation of this rule that's caused by a value type, have the method return the object as its return value. If the method must return multiple values, redesign it to return a single instance of an object that holds the values.
To fix a violation of this rule that's caused by a reference type, make sure that the behavior that you want is to return a new instance of the reference. If it is, the method should use its return value to do this.
Example
#pragma warning disable CA1045
// The code that's violating the rule is on this line.
#pragma warning restore CA1045When to suppress
It is safe to suppress a warning from this rule; however, this design could cause usability issues.