How to get address of a struct inside its method?

Viewed 283

I am able to get the address of a struct outside its (instance) method, as shown below:

public struct Values
{
    public byte A;
    public byte B;
    public byte C;
    public byte D;

    public static unsafe bool Equals(Values lhs, Values rhs)
    {
        return *(int*) &lhs == *(int*) &rhs;
    }
}

But when I try to get the address of the struct itself, the IDE tells me it's wrong:

    public unsafe bool Equals(Values other)
    {
        return *(int*) &this == *(int*) &other;
    }

The error message is:

You can only take the address of an unfixed expression inside of a fixed statement initializer.

The fixed statement prevents the garbage collector from relocating a movable variable. But this struct is not a movable variable, and will not be garbage collected, right?

Updated

What I actually need is to get/set the value of the Nth bytes by index. Although I can do it through switch statement, but it will be faster through index. Thanks to @KonradKokosa, Fixed Size Buffer meets my needs. I still want to know the answer to the main question.

1 Answers

You cannot take an address of this inside struct instance method because "this struct is not a movable variable" is not a true statement. Struct may be boxed, and thus immediately it becomes movable. Instance method does not know if it is called from boxed or not-boxed struct.

Note, it is currently a standing limitation also for ref structs, although it could be lifted. So, below code still produces the same compilation error:

public ref struct C {
    public void M() {
        var ptr = &this;
    }
}

However, you can take addresses of structs in a first snippet:

public static unsafe bool Equals(Values lhs, Values rhs)
{
    return *(int*) &lhs == *(int*) &rhs;
}

because you are taking here addresses of local arguments, passed by value (copies of Values, in the end).

Related