Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass by copy or reference?

I am a bit new to C# and was just wondering if there is a list of classes (commonly used) which are by default passed as copy. How can I identify them?

I know the basic basic object types — int, uint, float, strings, ... — are passed by copy.

like image 792
tvr Avatar asked Aug 24 '10 08:08

tvr


People also ask

Is pass by reference a copy?

In pass by reference (also called pass by address), a copy of the address of the actual parameter is stored.

Is it better to pass by reference or value?

Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument. When the called function read or write the formal parameter, it is actually read or write the argument itself.

What is difference between pass by reference and pass by value?

Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that's why it's called pass by value. Pass by Reference: An alias or reference to the actual parameter is passed to the method, that's why it's called pass by reference.

Is passing by reference good?

Passing value objects by reference is in general a bad design. There are certain scenarios it's valid for, like array position swapping for high performance sorting operations. There are very few reasons you should need this functionality. In C# the usage of the OUT keyword is generally a shortcoming in and of itself.


2 Answers

In C# / .Net objects can either be classified as value or reference types [1]. Value types are any type which derive from System.ValueType and are defined in C# with the struct type declaration. These are passed by copy / value.

Reference types are types which do not derive from System.ValueType and are defined in C# with the class keyword. Identifiers to instances of reference types are known as references (similar to pointers). These are also passed by value by default but only the reference is passed not the whole object.

Your question also mentioned that string instances are passed by copy. String in .Net is a reference type (derives directly from System.Object) and hence is not passed by full copy.

[1] Pointers may merit their own class here but I'm ignoring them for this discussion.

like image 200
JaredPar Avatar answered Oct 05 '22 12:10

JaredPar


All types, by default, are passed by value. The difference between value types (struct) and reference types (class) is that for value types a copy of the value is passed to the method, whereas for reference types, only a reference is passed.

See MSDN for more details.

Also, don't confuse the notion of value/reference types, and the notion of passing parameters by value or by reference. See this article by Jon Skeet for details

like image 42
Thomas Levesque Avatar answered Oct 05 '22 12:10

Thomas Levesque