Passing Property values by reference

October 14, 2008

Passing Property values by reference

I was wondering how well properties were integrated into C#.  For example, C# lets you use += with the properties.   It's easy enough to convert:
    MyProperty += 4
    MyProperty = MyProperty + 4

However, C# won't let you pass a property in as a ref parameter.  For example:
    void PassIntByRef(ref int x)
    PassIntByRef(ref MyProperty);
  <-- this is illegal in C#.

At first I thought C# was being lame. Afterall, why couldn't it do something like:
    int __temp = MyProperty;
    PassIntByRef(ref __temp); 
    MyProperty = __temp;

Then it hit me that was not correct behavior. Consider this example:

    int a = 5;
    PassPairByRef(ref a, ref a);

    void PassPairByRef(ref int x1, ref int x2) {
        x1++;         // 1) caller's reference to x1 (variable a) is immediately changed
        // since x1 and x2 are the same ref, x2 is changed too!
        // 2) So both x1 and x2 are now updated to 6

The naive codegen proposal above obviously would break down here. PassPairByRef  would need some pretty fancy codegen to handle a reference- property. The only way I can imagine is that it would effectively need a pair of delegates to the get_MyProperty  and set_MyProperty methods. That would codegen to something like:       

    delegate int Getter();
    delegate void Setter(int val);
    void PassPairByRef(Getter x1_get, Setter x1_set, Getter x2_get, Setter x2_set)
        x1_set(x1_get() + 1);
And then the callsite would look something like (this is pseudo-code):
            new Getter(get_MyProperty), new Setter(set_MyProperty), // ref for x1
            new Getter(get_MyProperty), new Setter(set_MyProperty)); // ref for x2

Since this is obviously less efficient than passing normal (non-property) values by-ref, the codegen would probably want two separate versions of the method: one for the normal case and one for properties.

Some random closing thoughts:
1. A higher-level language could certainly do this underneath the covers (and I bet out of the many .NET languages today, there are ones already that do).
2. I think in an alternative universe, the CLR also could have handled this too and allowed languages to directly pass properties as by-ref parameters. The CLR's JITter could handled the codegen above and even managing both versions of the target method; and it could even have an optimized way of indirectly calling get and set property methods.

출처 :

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram