C# Indexers with Ref Return Gets that also Support Sets
Asked Answered
M

1

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?

Mousterian answered 21/3, 2018 at 7:12 Comment(4)
I guess you understand that public ref byte this[int index] allows both get and set operations. Similar to public field.Antecedent
@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.Mousterian
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.Antecedent
@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.Mousterian
M
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.

Mousterian answered 7/5, 2018 at 9:14 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.