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?
- 1A quick Google search shows...Possible duplicate: C# field vs. property and Difference between Property and Field in C# 3.0+valverij– valverij2013-12-18 19:13:11 +00:00Commented Dec 18, 2013 at 19:13
- @Dhiren I have changed your title. Please take a look to make sure I didn't change the meaning of your question!dee-see– dee-see2013-12-18 19:15:59 +00:00Commented Dec 18, 2013 at 19:15
3 Answers
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.
1 Comment
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
int get_AField() and void set_AField(int value)). And you can't exactly do a ref on a function result.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.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