4

Consider this code:

struct Struct { public int Num; }

class Program
{
    public void A(ref readonly Struct s) { }
    public void B(ref readonly Struct s) => A(ref s);
}

I get a compilation error on this A(ref s), telling me:

CS8329: Cannot use variable as a ref or out value because it is a readonly variable

But the whole point of ref readonly is that you can guarantee it will not be changed. So why can't it be transitive?

Couldn't find helpful info in MSDN.

1 Answer 1

5

You should use the in modifier

class Program {
    public void A(ref readonly Struct s) { }
    public void B(ref readonly Struct s) => A(in s);
}

this is per the docs:

The ref readonly modifier isn't valid at the call site. Which modifier you use at the call site can help describe characteristics of the argument. You can only use ref if the argument is a variable, and is writable. You can only use in when the argument is a variable. It might be writable, or readonly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.