What is the difference between reference type and value type in C #?

Some guy asked me this question a couple of months ago, and I could not explain it in detail. What is the difference between reference type and value type in C #?

I know that the value types are int , bool , float , etc., and the reference types are delegate , interface , etc. Or is this also wrong?

Can you explain this to me professionally?

+80
c # value-type reference-type
Feb 20 '11 at 13:21
source share
14 answers

Your examples are a little strange, because while int , bool and float are defined types, interfaces and delegates are type types - just like struct and enum are value type types.

In this article, I wrote an explanation of reference types and value types . I would be happy to expand any bits you find confusing.

The TL; DR version should think about what a value of a variable / expression is of a particular type. For a value type, this value is the information itself. For a reference type, this value is a reference, which may be null or may be a way of navigating to an object containing information.

For example, think of a variable as a piece of paper. It may have a value of "5" or "false" written on it, but I could not have my house ... he should have directions to my house. These directions are equivalent links. In particular, two people could have different pieces of paper containing the same directions to my house - and if one person followed these directions and painted my house in red, then the second person will also see this change. If both of them had separate photographs of my house on paper, then one person who would color his paper would not change another personal paper at all.

+141
Feb 20 2018-11-21T00:
source share

Value Type:

Saves some values, not memory addresses

Example:

Struct

Storage:

TL; DR : a variable value is stored wherever it deviates. For example, local variables live on the stack, but when it is declared inside a class as a member, it lives on a heap that is closely related to the class in which it is declared.
Longer : In this way, value types are stored where they are declared. For example: the int value inside the function as a local variable will be stored on the stack, while the int value declared as a member in the class will be stored on the heap with the class in which it is declared. The value type in the class is of the lifetype type, which is exactly the same as the class in which it is declared, requiring almost no work as a garbage collector. This is more complicated, although I would call @JonSkeet’s book “ C # In Depth ” or his article “ Memory in .NET ” for a more concise explanation.

Benefits:

The value type does not require additional garbage collection. He receives the garbage collected along with the instance in which he lives. Local variables in methods are cleared when the method is released.

Disadvantages:

  1. When a large set of values ​​is passed to the method, the host variable is actually copied, so there are two redundant values ​​in memory.

  2. Because classes are overlooked. Loss of all benefits

Link Type:

Holds the memory address of a value not value

Example:

Class

Storage:

Saved in heap

Benefits:

  1. When you pass a reference variable to a method and it changes, it really changes the original value, whereas in the value types a copy of this variable is taken and this value is changed.

  2. When a variable is larger than the reference type, this is good

  3. Because classes are variables of a reference type, they provide reusability, which benefits object-oriented programming.

Disadvantages:

More references to work when distributing and dereferencing when reading a value. Additional overload for garbage collector

+18
Jul 11 '13 at 13:45
source share

It was easier for me to understand the difference between the two, if you know how the computer selects material in memory and knows what a pointer is.

A link is usually associated with a pointer. The value of the memory address where your variable is located actually contains a different memory address of the actual object in a different memory location.

The example I'm going to give is greatly simplified, so take it with salt.

Imagine that computer memory is a group of PO boxes in a row (starting from PO Box 0001 to PO Box n) that can hold something inside. If PO boxes do not do this for you, try a hash table or dictionary or array or something like that.

Thus, when you do something like:

var a = "Hello";

the computer will do the following:

  • allocate memory (for example, start at 1000 by 5 bytes) and put H (at 1000), e (at 1001), l (at 1002), l (at 1003) and o (at 1004).
  • allocate somewhere in memory (say, at location 0500) and assign it as a variable a.
    So it looks like an alias (0500 is a).
  • assign a value in this memory location (0500) to 1000 (where the beginning of the line Hello begins). Thus, the variable a holds the link to the actual starting memory location of the string "Hello".

The value type will contain the actual value in its memory location.

Thus, when you do something like:

var a = 1;

the computer will do the following:

  • select a memory location, for example, on 0500, and assign it to the variable a (the same alias)
  • put the value 1 in it (in memory location 0500).
    Please note that we do not allocate additional memory to store the actual value (1). So a actually holds the actual value and why he called the type of value.
+12
Feb 20 2018-11-21T00:
source share

This is from my post from another forum, about two years ago. Although the language is vb.net (unlike C #), the concepts of type type and link type are uniform throughout .net, and examples are still preserved.

It is also important to remember that inside .net all types are technically derived from the base type Object. Value types are intended to behave as such, but in the end they also inherit the functionality of the base Object type.

but. Value types are just that they represent a separate memory area in which the discrete value VALUE is stored. Value types have a fixed memory size and are stored on the stack, which is a set of addresses of a fixed size.

When you do this statement:

 Dim A as Integer DIm B as Integer A = 3 B = A 

You have done the following:

  • Created 2 spaces in memory, sufficient to store 32-bit integer values.
  • The value 3 is allocated in the memory allocation assigned to A
  • The value 3 is allocated in the memory allocation assigned to B, assigning it the same value as in A.

The value of each variable exists discretely in each memory cell.

B. Types of links can be of different sizes. Therefore, they cannot be stored in "Stack" (remember that a stack is a collection of fixed-size memory allocations?). They are stored in a managed heap. Pointers (or "links") to each element of the managed heap are stored on the stack (as an address). Your code uses these pointers on the stack to access objects stored in the managed heap. Therefore, when your code uses a reference variable, it actually uses a pointer (or "address" in a memory location in a managed heap).

Suppose you create a class called clsPerson with the string Property Person.Name

In this case, when you do this statement:

 Dim p1 As clsPerson p1 = New clsPerson p1.Name = "Jim Morrison" Dim p2 As Person p2 = p1 

In the above case, the p1.Name property will return Jim Morrison, as you would expect. The p2.Name property will also return Jim Morrison, as you would expect. I believe that both p1 and p2 are separate addresses on the stack. However, now that you have assigned p2 to p1, both p1 and p2 point to SAME LOCATION on the managed heap.

Now SAVE THIS situation:

 Dim p1 As clsPerson Dim p2 As clsPerson p1 = New clsPerson p1.Name = "Jim Morrison" p2 = p1 p2.Name = "Janis Joplin" 

In this situation, you created one new instance of the Person class in the Managed Heap with a pointer p1 on the stack that references the object, and again set the Name property of the object instance to Jim Morrison. Then you created another pointer p2 on the stack and pointed it to that same address in the managed heap as on p1 (when you made the assignment p2 = p1).

Here is a twist. When you set the Name property the value of p2 to "Janis Joplin", you change the Name property of the object, LINKS AND AND p1 and p2, so if you run the following code:

 MsgBox(P1.Name) 'Will return "Janis Joplin" MsgBox(p2.Name) 'will ALSO return "Janis Joplin"Because both variables (Pointers on the Stack) reference the SAME OBJECT in memory (an Address on the Managed Heap). 

Did that make sense?

The last one. If you do THIS:

 DIm p1 As New clsPerson Dim p2 As New clsPerson p1.Name = "Jim Morrison" p2.Name = "Janis Joplin" 

You now have two different Person objects. However, as soon as you do IT again:

 p2 = p1 

Now you have both pointed to Jim Morrison. (I'm not quite sure what happened to the object on the heap referenced by p2 ... I THINK that it is now out of scope. This is one of those areas where, hopefully, someone can install me directly .. .). -EDIT: I BELIEVE, which is why you should set p2 = Nothing OR p2 = New clsPerson before doing a new job.

Once again, if you do IT now:

 p2.Name = "Jimi Hendrix" MsgBox(p1.Name) MsgBox(p2.Name) 

Both msgBoxes will return "Jimi Hendrix"

This can be quite confusing, and I will say for the last time that some details may be wrong.

Good luck, and hopefully others who know better than me will come to help clarify some of these.,

+8
Feb 20 '11 at 17:52
source share

value data type and reference data types

1) value (directly contain data) but reference (refers to data)

2) in value (each variable has its own copy) but
in a link (more than a variable can refer to some objects)

3) in the value (the working variable cannot affect another variable) but in the link (the variable can affect others)

4) type values : (int, bool, float) but reference type : (array, class objects, string)

+3
Jan 01 '15 at 16:36
source share

"Variables based on value types contain values. Assigning one type variable to another value copies the contained value. This is different from assigning variables to a reference type that copies the reference to the object, but not the object itself." from the Microsoft library.

You can find a more complete answer here and here .

+1
Feb 20 '11 at 13:28
source share

Sometimes the explanations will not be especially useful for beginners. You can represent the value type as a data file and the reference type as a shortcut for the file.

So, if you copy the reference variable, you copy the link / pointer to the real data somewhere in memory. If you copy the value type, you really clone the data in memory.

+1
Apr 04 '17 at 6:38 on
source share

This is probably wrong for esoteric purposes, but to make it simple:

Value types are values ​​that are usually passed "by value" (therefore, copying them). Link types are passed "by reference" (so a pointer to the original value). The .NET ECMA standard does not guarantee that these “things” are preserved. You could create a .NET implementation that does not contain stacks, or uncomplicated (the second would be very complex, but you could probably use fibers and many stacks)

Structures are a value type (int, bool ... are structures, or at least mimics like ...), classes are a reference type.

Value types are descended from System.ValueType. Link type descends from System.Object.

Now .. In the end, you have a Value Type, "reference objects" and links (in C ++ they will be called pointers to objects. In .NET they are opaque. We don’t know what they are. They "process" the object ) These values ​​are similar to value types (they are transferred by copy). Thus, an object consists of an object (reference type) and zero or more references to it (similar to value types). When there are null references, GC is likely to collect it.

In the general case (in the "standard" .NET implementation), the value type can be on the stack (if these are local fields) or on the heap (if they are class fields, if they are variables in an iterator, if they are variables referenced by the closure if they are variables in an asynchronous function (using the newer Async CTP) ...). The specified value can go only to the heap. References use the same rules as value types.

In cases of type values ​​that go on the heap because they are in the iterator function, the async function either refers to closure, if you look at the compiled file, you will see that the compiler created a class to put these variables, and the class will be created when you call the function.

Now I don’t know how to write long things, and I have the best things in my life. If you want the “exact” “academic” “correct” version, read THIS:

http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx

It's 15 minutes, I'm looking for him! This is better than msdn versions because it is a concise "ready to use" article.

0
Feb 20 '11 at 13:29
source share

The easiest way to think about reference types is to think of them as "object identifiers"; the only thing that can be done with the object identifier is to create one, copy one, recognize or manipulate the type of one, or compare two for equality. Attempting to do something else with the object identifier will be considered an abbreviation for performing the specified action on the object to which this identifier refers.

Suppose I have two variables X and Y of type Car - a reference type. Y is the "Object ID No. 19531". If I say “X = Y”, this will force X to hold “Object ID No. 19531”. Please note: neither X nor Y hold the car. The car, otherwise known as "Object ID No. 19531", is stored elsewhere. When I copied Y to X, all I did was copy the ID number. Now suppose I say X.Color = Colors.Blue. Such an expression will be considered as an instruction to find "Object ID No. 19531" and draw it in blue. Note that although X and Y now refer to a blue car rather than yellow, the statement does not actually affect X or Y, because both still refer to “object ID # 19531”, which still remains the same car, which has always been.

0
Mar 16 '11 at 18:37
source share

Variable types and reference value are easy to apply and apply well to the domain model, facilitate the development process.

To remove any myth around the “value type” sum, I will comment on how this is handled on the platform. NET, in particular, in C # (CSharp) when calling APIS and sending parameters by value, by reference, in our methods and functions, and how to correctly handle passes of these values.

Read this article Value and Reference of Variable Type in C #

0
Apr 24 '13 at 1:32
source share

Suppose v is an expression / variable of type value, and r is an expression / variable of reference type

  x = v update(v) //x will not change value. x stores the old value of v x = r update(r) //x now refers to the updated r. x only stored a link to r, //and r can change but the link to it doesn't . 

So, a value type variable stores the actual value (5 or "h"). A reference type template only stores a reference to a metaphorical field where this value is.

0
Jul 17 '14 at 6:07
source share

Simply put, value types are passed by their value and reference types by their reference (memory address).

This means that changes made to parameters of the value type (formal parameters) inside the called method will not be reflected in the values ​​from which the method was called (actual parameters).

But the changes made to the reference parameters inside the called method will be reflected in the changes to the variables declared in the calling method.

This is a brief explanation. See here for a detailed understanding of value types, reference types, and value types compared to a reference type.

0
Dec 28 '15 at 7:41
source share

Value Type:

  • The size of the fixed memory.

  • Stored in the memory of the stack.

  • Saves the actual value.

    Ex. int, char, bool, etc ...

Link Type:

  • Not a fixed memory.

  • Stored in heap memory.

  • Saves the memory address of the actual value.

    Ex. string, array, class, etc ...

0
May 7 '18 at 11:21
source share

There is no difference between value types and reference types, there are many small details that are explicitly specified by the standard, and some of them are not easy to understand, especially for beginners.

See ECMA Standard 33, Common Language Infrastructure (CLI). CLI is also ISO standardized. I would provide a link, but for ECMA we need to download a PDF file, and this link depends on the version number. ISO standards cost money.

One of the differences is that value types can be in the box, but there can be no reference types at all. There are exceptions, but they are pretty technical.

Value types cannot have instance constructors without parameters or finalizers, and they cannot refer to themselves. Turning to ourselves, for example, means that if there is a value type of Node, then a member of a node cannot be a node. I think there are other requirements / limitations in the specifications, but if so, they are not coming together in one place.

0
May 17 '18 at 22:24
source share



All Articles