1

I have this code:

private int _someProperty;
public int SomeProperty
{
    get => _someProperty;
    set => SetProperty(ref _someProperty, value);
}

private void SetProperty<T>(ref T field, T value)
{
    if (!field.Equals(value))
    {
        field = value;
    }
}

I need the SetProperty<T> because I need a set logic in a big class with lots of properties, and that logic applies to all of them. The code works for the case of _somePropertybeing a variable. But in my case, it does not work because I reference to another property of a nested class, so I get the compilation error: "a property or indexer may not be passed as an out or ref parameter".

As properties are methods under the hood, I tried something like:

private setProperty<T>(ref Action<T> property, T value) {
    //meaningful code
}

But I get the compilatuion error anyhow.

Is there a direct way to pass a property by reference to directly solve this problem somehow?

rustyBucketBay
  • 4,320
  • 3
  • 17
  • 47

1 Answers1

5

No, basically.

There is a potential loophole around mutable ref-returning get-only properties, but that probably won't help you because:

  1. you can't have any set logic in a mutable ref-returning get-only property
  2. this is an absurdly niche scenario that the majority of devs don't know exists, and will never need to use :)
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 2
    @TheGeneral just be warned: you cannot unsee. At your choice: https://gist.github.com/mgravell/c46a1de553abe325dea0c44ac7fa7766 - note, this isn't the usual usage of this language feature, as in this case it is pretty much the same as exposing the field directly. A more typical usage might be for a flyweight, or to provide controlled access (by-ref) to values inside an array/etc; if it had existed at the time, `ArraySegment` could have had an indexer `public ref T this[int index] => ref Array[Offset + index];`, for example – Marc Gravell Aug 06 '20 at 09:32
  • 1
    @TheGeneral what's *really* fun; did you know that there's actually a `foreach` syntax for custom iterators that have ref-return of `.Current`, that allows you to mutate the foreach iteration variable (usually raises CS1656)? https://gist.github.com/mgravell/db3e63c2f8cea1866a6aaade7507fa18 – Marc Gravell Aug 06 '20 at 09:44
  • hah cool, that's fairly intersting. If I could upvote again I would – TheGeneral Aug 06 '20 at 09:47
  • You could do an adults-only after dark blog for c#, that second one seems like a one way street to Benign error town. I like it though! – TheGeneral Aug 06 '20 at 09:59