I would like to be able to refer to a variable inside an instance of the class, but I would like the link to become a class variable, so I don't need to send it inside the class as a parameter
Then you have to live with disappointment. A CLR system explicitly prohibits storing variable references as members of classes. CLR allows you to refer to variables as
- passed to methods as arguments corresponding to formal parameters, or 'this'
- saved as local
- returned as method return values
but does not allow storing in arrays, fields, etc. In principle, everything that goes "a bunch" cannot contain links.
C # provides the first function: refers to variables as method parameters. It does not reveal two other functions (although I wrote an experimental version of C # that works, and it works pretty well.)
Note that C # does not allow refs to be used in contexts that require storage of the ref ref heap, for example, the ref parameter, which is a private external lambda variable, for example. There are a few rare cases where the compiler resolves what looks like long-term storage of ref and uses copy-in-copy-out semantics to emulate a link, but it's probably best not to go there.
Why does the CLR have this limitation? The right way to think about the fact that there are two types of storage: long-term and short-term, usually called "heap" and "stack". But the form of the data structure does not matter; length of life matters. The variable has a storage location; what a variable. If you can keep a reference to a variable extracted from a short-term storage in a long-term storage, then a long-term storage stores a link to something that has a shorter lifespan, and therefore it may crash and die when accessing a variable after its death.
Obviously, there are many ways to solve this problem. For example, the CLR team could make it illegal to get a short-term storage link and allow link storage in long-term storage. But this means that you cannot accept references to local variables or parameters that you would like to place in the short-term storage, because their life is so short.
The way the CLR team actually chose is to prohibit the long-term storage of any links. Like any design decision, this was the result of many trade-offs against competing goals.
Eric Lippert
source share