Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties - by value or reference?

I've got the following public property which exposes an Arraylist:

public ArrayList SpillageRiskDescriptions
        {
            get
            {
                return _SpillageRiskDescriptions;
            }
            set
            {
                _SpillageRiskDescriptions = value;
            }
        }

Elsewhere I'm calling

SpillageRiskDescriptions.Add("VENTILATE AREA");
SpillageRiskDescriptions.Add("DO NOT ALLOW SPILLAGE TO ENTER MAINS");

These seem to be adding elements to the private ArrayList _SpillageRiskDescriptions (through the property) whereas I would've expected this to cause a problem. Therefore am I correct in thinking that properties return a reference to the original variable and not passing it by value? Is this because ArrayList is a reference type? Will the same happen with an int (for example?)

like image 806
m.edmondson Avatar asked Mar 11 '11 15:03

m.edmondson


1 Answers

Technically it's always by value, but you have to understand what is being passed. Since it's a reference type, you are passing a reference back (but by value).

Hope that makes sense. You always pass the result back by value, but if the type is a reference you are passing the reference back by value, which means you can change the object, but not which object it refers to.

like image 141
James Michael Hare Avatar answered Sep 20 '22 13:09

James Michael Hare