Alex Rivera | Logout

Is it possible to pass properties as "out" or "ref" parameters?

Asked 2009-02-19T09:43:26.620
35

Can I pass a property as an "out" or "ref" parameter if not then why not?

e.g.

Person p = new Person(); 

. . .

public void Test(out p.Name);
Edit
Report

1 Answer

15

Others have explained that you can't do this in C#. In VB.NET, you can do this, even with option strict/explicit on:

Option Strict On
Option Explicit On
Imports System.Text

Module Test

   Sub Main()
       Dim sb as new StringBuilder
       Foo (sb.Length)
   End Sub
   
   Sub Foo(ByRef x as Integer)
   End Sub
    
End Module

The above code is equivalent to this C# code:

using System.Text;

class Test
{
     static void Main()
     {
         StringBuilder sb = new StringBuilder();
         int tmp = sb.Length;
         Foo(ref tmp);
         sb.Length = tmp;
     }

     static void Foo(ref int x)
     {
     }
}

Personally I'm glad that C# doesn't have this - it's muddying the waters quite a lot, particularly in terms of the value of the property if the parameter is set within the method but then an exception is thrown.

EDIT: As requested, my reasoning as to why I believe passing properties in muddies the waters. If you pass a normal variable by reference, then that variable is evaluated every time it is referenced within the method. If the value changes for some reason (e.g. as a side-effect of some other work in the method) then that change will be immediately visible in the method. That's not the case if you pass a property by reference in VB.NET: the property getter is invoked once, and then the property setter is invoked once. It's not like you're passing in "here's a property - get and set from that whenever you use the parameter."

Here's a full example where passing a field and passing an entirely trivial property in .NET have very different results:

Option Strict On
Option Explicit On
Imports System.Text

Class Test

   Dim counter as Integer
   
   Property CounterProperty As Integer
       Get
           Return counter
       End Get
       Set (ByVal value as Integer)
           counter = value
       End Set
   End Property
  
answered 2009-02-19T11:09:32.793

Your Answer