Pass a copy or link?

I'm a little new to C #, and I'm just wondering if there is a list of classes (commonly used) that are passed as copy by default. How can I identify them?

I know that the basic base types of objects - int, uint, float, string, ... - are passed in by copy.

+4
source share
4 answers

In C # /. Net objects, they can be classified as values ​​or reference types [1]. Value types are any types that are inferred from System.ValueType and defined in C # with a declaration of type struct . They are transmitted by copy / value.

Reference types are types that are not related to System.ValueType and are defined in C # with the class keyword. Identifiers for instances of reference types are called references (similar to pointers). They are also passed by default, but only the link is not passed by the whole object.

Your question also mentioned that string instances are passed by copy. string in .Net is a reference type (derived directly from System.Object ) and, therefore, is not passed in as a complete copy.

[1] Pointers may deserve their own class, but I ignore them for discussion.

+15
source

All types are passed by default by default. 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, while for reference types only the reference is passed.

See MSDN for more details .

Also, do not confuse the concept of value / reference types and the concept of passing parameters by value or by reference. See this article by Jon Skeet for more details.

+10
source

In general

  • types of values, which include native types ( int , float , ...), as well as struct are transferred by "copy" (as you put it), whereas

  • reference types that include class es, only the link is copied instead of the full object.

Please note that this string is not transmitted as a "copy"! This is a reference type, but since it is immutable, it behaves similarly to a value type .

Note that the ref keyword can be useful in both cases: in the case of value types, this means that the value is copied back. In the case of reference types, this means that the link can be changed (i.e. you can assign a variable to a new object, and not just change the properties of the object.)

+3
source

Note that structure objects may include reference types:

 struct Currency { int Amount {get;set;} // is referenced by value (copy) string Code {get;set;} // is referenced by reference } 

When you use this structure as follows:

 var obj1 = new Currency{Amount = 1, Code = "USD"}; var obj2 = obj1; 

Then

 object.ReferenceEquals(obj1.Code, obj2.Code); // false - string is reference type, but used inside value type 

If you declared Currency as a class, the references to Code were the same.

+2
source

All Articles