e01.org

Value type and reference type

In certain computer programming languages, data types are classified as either value types or reference types, where values referenced by reference type variables are always implicitly accessed via references stored in those variables, whereas value type variables directly contain the values themselves. Source: e01 Encyclopedia. Licence: CC BY-SA 4.0.

In certain computer programming languages, data types are classified as either value types or reference types, where values referenced by reference type variables are always implicitly accessed via references stored in those variables, whereas value type variables directly contain the values themselves. class Foo { public int a; } Foo a = new Foo(); Foo b = a; a.prop = 3; a = new Foo(); a.prop = 1; Foo is a reference type, where a is initially assigned a reference of a new object, and b is assigned to the same object reference, i.e. bound to the same object as a , therefore, changes through a is also visible to b as well. Afterwards, a is assigned a reference (rebound) to another new object, and now a and b refer to different objects. At the end, a refers to the second object with its prop field having the value 1 , while b refers to the first object with its prop field having the value 3 . However, such as C++, the term "reference type" is used to mean an alias, and it is not possible to rebind a variable of a reference type once it is created, as it is an alias to the original object. class Foo { public: int a; }; Foo a; a.prop = 1; Foo& b = a; Foo c = a; a.prop = 3; In C++, all non-reference class types have value semantics. In the above example, b is declared to be a reference (alias) of a , and for all purposes, a and b are the same thing. It is impossible to rebind b to become something else. After the above example is run, a and b are the same Foo object with prop being 3 , while c is a copy of the original a with prop being 1 . In C#, apart from the distinction between value types and reference types, there is also a separate concept called reference variables. A reference variable, once declared and bound, behaves as an alias of the original variable, but it can also be rebounded to another variable by using the reference assignment operator = ref . The variable itself can be of any type, including value types and reference types, i.e. by passing a variable of a reference type by reference (alias) to a function, the object where the reference-type variable points to can also be changed, in addition to the object itself (if it is mutable).

source: e01 Encyclopedia · licence: CC BY-SA 4.0 · page · source revision

Cite this

"Value type and reference type". 1772900456. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1342201858

JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy

Save to pass ·