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?

dee-see
  • 21,841
  • 5
  • 54
  • 87
Dhiren
  • 398
  • 1
  • 2
  • 10
  • 1
    A quick Google search shows...Possible duplicate: [C# field vs. property](http://stackoverflow.com/questions/8773181/c-sharp-field-vs-property) and [Difference between Property and Field in C# 3.0+](http://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp-3-0) – valverij Dec 18 '13 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 Dec 18 '13 at 19:15

3 Answers3

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.

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
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; }
  • 3
    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. – Scott Chamberlain Dec 18 '13 at 19:16
  • 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. – O. R. Mapper Dec 18 '13 at 19:32
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
Will Faithfull
  • 1,789
  • 12
  • 20