6

Am I doing something wrong here, or as of C# 7.2 Indexers that return by ref and allow set are not supported?

Works:

public ref byte this[int index] {
  get {
      return ref bytes[index];
  }
}

Works too:

public byte this[int index] {
  get {
      return bytes[index];
  }
  set {
    bytes[index] = value;
  }
}

Fails:

public ref byte this[int index] {
  get {
      return ref bytes[index];
  }
  set { //<-- CS8147 Properties which return by reference cannot have set accessors
    bytes[index] = value;
  }
}

Fails too:

public ref byte this[int index] {
  get {
      return ref bytes[index];
  }
}

public byte this[int index] { //<-- CS0111 Type already defines a member called 'this' with the same parameter types
  set {
    bytes[index] = value;
  }
}

So, is there no way to have a ref return yet allow the indexer also support Set?

Fit Dev
  • 3,413
  • 3
  • 30
  • 54
  • I guess you understand that `public ref byte this[int index]` allows both get *and* set operations. Similar to public field. – Ivan Stoev Mar 21 '18 at 09:47
  • @IvanStoev Yes. But apparently I cannot have both Get and Set (if `ref` is used). That's what I was trying to do in the first place. – Fit Dev Mar 21 '18 at 12:34
  • 2
    That should be obvious from my previous comment. Once I get `ref byte` from your indexer, I can assign a value to it, and no setter will be involved (because I have basically a pointer to your underlying data buffer). Hence having a setter makes no any sense. – Ivan Stoev Mar 21 '18 at 13:05
  • 1
    @IvanStoev Oh yes, you are right! How silly of me! You should then just post it as an answer which I will gladly accept! Thanks. – Fit Dev Mar 22 '18 at 13:20

1 Answers1

3

As @IvanStoev correctly pointed out, there is no need for set, since the value is returned by reference. Therefore the caller of the indexer has complete control over the returned value and can therefore can assign it a new value, with the changes being reflected in the underlying data structure (whose indexer was being called) since the value was returned by reference and not by value.

Fit Dev
  • 3,413
  • 3
  • 30
  • 54