Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a property can not be passed as out parameter?

For example:

    int? qID= null;

    answer.QuestionID = int.TryParse(lblID.Text, out qID.Value) ? qID : null; //Error: Property or Indexer may not be passed as an out ot ref parameter.

From microsoft documentation it says that:

"A variable passed as an out argument need not be initialized. However, the out parameter must be assigned a value before the method returns."

and then:

"A property is not a variable and cannot be passed as an out parameter.

So what was the reasoning in the underlying .net platform design to prohibit from setting a property of an object via the out? The value of out does not have to be a reference object either - totally legit to use a value type. So why not?

like image 648
dexter Avatar asked Jan 27 '11 17:01

dexter


2 Answers

This is valid in VB, but not in C#... VB effectively creates a temporary local variable for you, calls the method passing in the local variable as the argument, and then sets the property with the value of the local variable. C# doesn't usually hide that sort of thing for you.

The method itself needs a variable as the out parameter. It's got to have a storage location it can just write values to. Not a property, not anything it needs to invoke: just a storage location. A property doesn't satisfy that requirement. So there's nothing that can be done by the compiler in the method to allow this.

So either the compiler has to fake it with a temporary variable, as per VB, or disallow it, as per C#. Personally I prefer the C# approach - otherwise it looks as if each time the method assigned a value to the out parameter, the property would be set - which certainly isn't the case.

like image 186
Jon Skeet Avatar answered Oct 26 '22 21:10

Jon Skeet


A property is just a pair of functions named get_Something and set_Something.
An out parameter takes a reference to a field or a variable; it wouldn't make any sense to pass a pair of functions.

VB.Net can pass properties as ByRef parameters; the compiler generates a temporary variable and re-assigns the proeprty to the variable after calling the method.

However, even VB.Net cannot handle your case, because the Nullable<T>.Value property is read-only.

like image 37
SLaks Avatar answered Oct 26 '22 22:10

SLaks