3

What makes properties and Fields different when we are passing Fields as an out/ref parameter . Does the difference between the two is memory allocation?

2

3 Answers 3

4

The biggest difference is that properties or indexers may not be passed as ref or out parameter (demo).

This is because properties do not necessarily have a backing storage - for example, a property may be computed on the fly.

Since passing out and ref parameters requires taking variable's location in memory, and because properties lack such location, the language prohibits passing properties as ref/out parameters.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks..thats quite sums up
2

Properties are not like fields at all, they're like methods.

this is a field; it does not have any logic.

private int _afield; 

This is a property it defines a getter and a setter.
The getter and setter are methods.

public int AField { get { return _aField; } set { _aField = value; } } 

This is a default property.
It's exactly like the previous property and field, except it does a lot of the work for you

public int BField { get; set; } 

2 Comments

They are not just like methods, they are methods! The compiler internally creates two methods for your property getter and setter (int get_AField() and void set_AField(int value)). And you can't exactly do a ref on a function result.
All of your explanations seem correct. Just note that strictly speaking, that is not a reason why they cannot be used for ref or out parameters - the language could well be defined in a way so as to translate any access to the respective parameter to the appropriate method calls for the property.
0

The best way to describe properties is in terms of the idiom of "getter" and "setter" methods.

When you access a property, you are actually making a call to a "get" method.

Java

private int _myField; public int getMyProperty() { return _myField; } public int setMyProperty(int value) { _myField = value; } int x = getMyProperty(); // Obviously cannot be marked as "out" or "ref" 

C#

private int _myField; public int MyProperty { get{return _myField;} set{_myField = value;} } int x = MyProperty; // Cannot be marked as "out" or "ref" because it is actually a method call 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.