Note that there are some explanatory texts on larger screens.

plurals
  1. POC# property and ref parameter, why no sugar?
    primarykey
    data
    text
    <p>I just ran across this error message while working in C#</p> <blockquote> <p>A property or indexer may not be passed as an out or ref parameter</p> </blockquote> <p>I known what caused this and did the quick solution of creating a local variable of the correct type, calling the function with it as the <code>out</code>/<code>ref</code> parameter and then assigning it back to the property:</p> <pre><code>RefFn(ref obj.prop); </code></pre> <p>turns into</p> <pre><code>{ var t = obj.prop; RefFn(ref t); obj.prop = t; } </code></pre> <p>Clearly this would fail if the property doesn't support get and set in the current context.</p> <p>Why doesn't C# just do that for me?</p> <hr> <p>The only cases where I can think of where this might cause problems are:</p> <ul> <li>threading</li> <li>exceptions</li> </ul> <p>For threading that transformation affects when the writes happen (after the function call vs. in the function call), but I rather suspect any code that counts on that would get little sympathy when it breaks.</p> <p>For exceptions, the concern would be; what happens if the function assigns to one of several <code>ref</code> parameters than throws? Any trivial solution would result in all or none of the parameters being assigned to when some should be and some should not be. Again I don't think this would be supported use of the language.</p> <hr> <p>Note: I understand the mechanics of why this error messages is generated. What I'm looking for is the rationale for why C# doesn't automatically implement the trivial workaround.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload