How to understand pining static field, const and instance field
I am learning unsafe C#, and trying to understand when to use
fixed
statement. Here's the example:
The question is, why can I pin a static field? Is it because static field live during the whole cycle, so it's managed?
And what about const
, is it because const isn't a variable or field so simply can't get the address?
And for instance field, since it's fixed inside the instance method, so ...? I don't really know how to explain this.
Please let me know if I understand them wrong, thank you!4 Replies
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
static fields have no requirement to live in pinned memory, so you have to pin them, and consts don't have a memory location
consts are copied into all the places you use them, they aren't "fields"
I found a description from documentation
Note: As stated in §12.8.7, outside an instance constructor or static constructor for a struct or class that defines a readonly field, that field is considered a value, not a variable. As such, its address cannot be taken. Similarly, the address of a constant cannot be taken.
Unsafe code - C# language specification
This chapter describes elements of C# that are allowed in unsafe code blocks. These elements include pointers, fixed buffers and dynamic memory allocation.