First, the answers of John, Michael, and Jared are mostly correct, but I have a few more things that I would like to add to them.
What is meant by the "unclean" method?
Itβs easier to characterize clean methods. The "pure" method has the following characteristics:
- His conclusion is completely determined by his input; its output does not depend on external factors, such as time of day or bit on the hard drive. His exit does not depend on his story; calling the method with the given argument twice should give the same result.
- The pure method does not produce observed mutations in the world around it. A pure method may choose to mutate a particular state for efficiency, but a pure method, say, does not change the field of its argument.
For example, Math.Cos is a clean method. Its output depends only on its input, and the input does not change when called.
The impure method is a method that is not pure.
What are some of the dangers of passing readonly structures to unclean methods?
There are two that come to mind. The first is the one that John, Michael, and Jared pointed out, and this is the one that Reshar warns you about. When you call a method in a struct, we always pass a reference to the variable that is the recipient in case the method wants to change this variable.
So what if you call such a method by value and not by variable? In this case, we create a temporary variable, copy the value into it and pass the link to the variable.
The readonly variable is considered a value because it cannot be changed outside of the constructor. Thus, we copy the variable to another variable, and an unclean method may mutate the copy when you intend to change it.
This is the danger of transmitting the readonly structure as a receiver. There is also the danger of passing a structure containing a readonly field. A structure containing a readonly field is common practice, but it is basically written to verify that the type system has no cash; The read-only of a specific variable is determined by the owner of the repository. An instance of a reference type "owns" its own store, but an instance of a type does not!
struct S { private readonly int x; public S(int x) { this.x = x; } public void Badness(ref S s) { Console.WriteLine(this.x); s = new S(this.x + 1);
Someone thinks that this.x will not change, because x is a read-only field, and Badness not a constructor. But...
S s = new S(1); s.Badness(ref s);
... clearly demonstrates the falsity of this. this and s refer to the same variable, and this variable is not readonly!