Passing object as value  
Author Message
Me_Titus





PostPosted: Visual C# General, Passing object as value Top

Hi you all,

rearding the following code:

<code>

ArrayList parties = new ArrayList();

ArrayList arrayAux = new ArrayList();

arrayAux.Add((Point)outterPoints[outterIndex]);

arrayAux.Add((Point)innerPoints[(int)pointsInDistance[0]]);

arrayAux.Add((Point)innerPoints[(int)pointsInDistance[1]]);

arrayAux.Add((Point)getPartyCenter(arrayAux));

parties.Add(arrayAux);

arrayAux.Clear();

</code>

If I print the values in the parties ArrayList I wont get any values, but If I instead do the folowing:

<code>

...

parties.Add(arrayAux.Clone());

arrayAux.Clear();

</code>

I will get the values I am expecting. Are the array being passed as a reference in the first case And if you is this the default Are there any reserved words for passing object as references or as values

Thanks in advance,

MeTitus



Visual C#8  
 
 
RizwanSharp





PostPosted: Visual C# General, Passing object as value Top

Yes Arrays/classes are dealt as reference types in C# when you Clear the arrayAux with Clear method then referenced array/objects are cleared and you get nothing in parties.

But the other way you are using Clone(), creates a sperate copy and add this copy of collection to parties so the original copy is cleared without affecting it.

The point to note here is: Arrays/classes are reference types in C#.

Best Regards,

Rizwan



 
 
Me_Titus





PostPosted: Visual C# General, Passing object as value Top

But is there any other way to archieve this, or the best way is o use the clone method of an object... and is there any way i can pass a class by value

Thanks,

MeTitus


 
 
RizwanSharp





PostPosted: Visual C# General, Passing object as value Top

Clone creates a seperate copy of the object so this is OK and you need to do it, There is no other way to directly pass a ref type as value to some function.

objects of classes are shellow copied when passed to some functions or assigned to some other object.

Shellow Copying: Only Reference is copied not completely the object.

Deep Copying: The whole object is replicated as in case of value types.

Best Regards,

Rizwan