Search code examples
c#thisunsafeindexerunsafe-pointers

Accessing "this" pointer/reference using an indexer in C#


I am experimenting with a datastructure for a performance / memory critical part of our codebase. I would like to have a fast access to the bytes defined in the structure. However I am not sure how to access the structure on which I am operating on using the indexer.

[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Foo
{
    [SerializeField]
    private byte a, b, c;

    public unsafe byte this[byte index]
    {
        get
        {       
            //omitted safety checks   

            //this is a no, no
            byte* addr = (byte*)&this;

            return addr[index];
        }
    }
}

Solution

  • You can only do what you're trying to do inside a fixed block, i.e.:

    fixed (Foo* foo = &this)
    {
        byte* addr = (byte*)foo;
        return addr[index];
    }