Is "readonly" meaningful on a getter-only ref struct property in an interface?

Viewed 94

If I have an interface that specifies ref readonly on a property that only has a getter, is this readonly in any way meaningful, i.e. is it redundant?

struct Foo
{
}

interface IBar
{
    ref readonly Foo F { get; }
}
2 Answers

I think I have figured it out.

The getter returns the reference to a referred variable. If the ref is not declared as readonly, the caller that got the reference can still modify the variable. So, yes, readonly is meaningful.

I think the case where readonly is redundant only when the struct itself is already declared as readonly.

There ref and interface here are superfluous... In any-case you are getting a ref regardless in your example. The only significant difference omitting readonly would make on a get only property within a non-readonly struct is with the in parameter, the compiler will make a defensive copy of the parameter for each instance member invocation

As shown here

Given

public struct Foo
{
   private readonly int[] _array ;
   public Foo(int[] array ) => _array = array;     
   public readonly ref int this[int i] => ref _array[i];
}

public  struct Foo2
{
   private readonly int[] _array ;
   public Foo2(int[] array ) => _array = array;     
   public ref int this[int i] => ref _array[i];
}

...

public float M(in Foo value) => value[0] + value[1];

public float M2(in Foo2 value) =>  value[0] + value[1];

The emitted IL would equate to

public float M([In] [IsReadOnly] ref Foo value)
{
    return value[0] + value[1];
}

public float M2([In] [IsReadOnly] ref Foo2 value)
{
    Foo2 foo = value;
    int num = foo[0];
    foo = value;
    return num + foo[1];
}
Related