© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
9 replies
wtq40cy3n

How to understand pining static field, const and instance field

I am learning unsafe C#, and trying to understand when to use
fixed
fixed
statement. Here's the example:
class K { public int k; }
struct C
{
    public int instanceMember;
    public readonly static int shared;
    public const int con = 0;
    unsafe void M(int j, K k)
    {
        fixed (int* p = &j) { } // CS0213
        fixed (int* p = &k.k) { }
        int local = 0;
        fixed (int* p = &local) { } // CS0213
        int[] localArray = [];
        fixed (int* p = localArray) fixed (int* pp = p) { } // CS8385
        string localString = "abc";
        fixed (char* p = localString) fixed (char* pp = p) { } // CS8385
        K kk = new();
        fixed (int* p = &kk.k) { }
        fixed (int* p = &this.instanceMember) { }
        fixed (int* p = &C.shared) { }
        fixed (int* p = &C.con) { } // CS0211
    }
}
class K { public int k; }
struct C
{
    public int instanceMember;
    public readonly static int shared;
    public const int con = 0;
    unsafe void M(int j, K k)
    {
        fixed (int* p = &j) { } // CS0213
        fixed (int* p = &k.k) { }
        int local = 0;
        fixed (int* p = &local) { } // CS0213
        int[] localArray = [];
        fixed (int* p = localArray) fixed (int* pp = p) { } // CS8385
        string localString = "abc";
        fixed (char* p = localString) fixed (char* pp = p) { } // CS8385
        K kk = new();
        fixed (int* p = &kk.k) { }
        fixed (int* p = &this.instanceMember) { }
        fixed (int* p = &C.shared) { }
        fixed (int* p = &C.con) { } // CS0211
    }
}

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
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!
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ How do I understand static typing
C#CC# / help
2y ago
✅ How to make static field required to use from interface?
C#CC# / help
11mo ago
A const field requires a value to be provided
C#CC# / help
2mo ago
❔ Static Field get not called!
C#CC# / help
4y ago