C #1 core infrastructure (2)-value type and reference type

Source: Internet
Author: User

In. NET is actually dealing with a value type or reference type, but it is very likely that some people have been using C # For a long time, these differences are just a vague concept. Even worse, there may be some misunderstandings. It is easy to make a short but incorrect statement without being careful. Here I will briefly discuss the theme elements of C #1 which must be understood to go deep into the world of C # later.

Let's take a look at how the basic differences between value types and reference types are embodied in the real world and in. NET.

Values and references in the real world

Suppose you are reading a newspaper. To give a copy to a friend, you need to copy all the contents of the newspaper and give it to him. In this way, he will obtain a complete copy of his own. In this case, we are dealing with value-type behavior. Copies of your newspaper and friends are independent of each other. You can add comments or draw pictures in your newspaper. Your friend's newspaper will not change at all.

Let's assume that you are browsing a webpage. Compared with the previous one, the only one that needs to be given to a friend is the URL of the webpage. This is a behavior of the reference type, and the URL replaces the reference. To read a document, you must enter a URL in the browser and require it to load the webpage for navigation and reference. On the other hand, if the webpage changes for some reason, you and your friends will see the change the next time they load the page.

In C # And. NET, the differences between value types and reference types are similar to those in the real world .. . NET. Except for the following special cases, classes (declared using class) are reference types, while structures (declared using struct) are value types.

Special situations include:

1) The array type is a reference type, even if the element type is a value type (So int [] is still a reference type, even if int is a value type );

2) enumeration (declared using enum) is a value type;

3) The delegate type (declared using delegate) is the reference type;

4) the interface type (declared by interface) is a reference type, but can be implemented by a value type.

When learning value types and reference types, you must master the important concept of what is the value of a special expression. To make the problem more specific, I used the most common example of an expression-variable. However, the same principle applies to attributes, method calls, indexers, and other expressions.

For a value-type expression, its value is the value of the expression, which is easy to understand. For example, the value of the expression "3 + 2" is 5. However, for an expression of the reference type, its value is a reference, rather than the object referred to by the reference. Therefore, the value of String. Empty is not an Empty String, but a reference to the Null String.

To further illustrate this problem, let's take a look at a Point type that stores two integers x and y. One of its constructors can obtain two values. Now, this type can be implemented as a structure or class. The result of executing the following two lines of code is displayed.

In both cases, p1 and p2 both have the same "value" after being assigned a value ". However, when Point is a reference type, the "value" is reference: p1 and p2 both reference the same object. When Point is a value type, the p1 value is the complete data of a "Point", that is, the x and y values of this "Point. If the value of p1 is assigned to p2, all data of p1 will be copied.

It is worth noting that the value of a variable is stored at the position it declares. The values of local variables are always stored in the stack (this argument is only true in C #1. in C # Later versions, under specific circumstances, local variables may eventually be stored on the heap ). The value of the instance variable is always stored in the place where the instance itself is stored. Reference instances (objects) are always stored in heap, and static variables are also used.

Another difference between the two types is that the value type cannot be derived from other types. The result is that no additional information is required for the value to describe the actual type. Compare it with the reference type. For the reference type, each object contains a data block at the beginning, which identifies the actual type of the object and provides other information.

The above describes the value type and reference type. I believe that those who carefully read the value type and reference type have a certain understanding of the value type and reference type. Many people may have some misunderstandings about packing and unpacking. The following is a simple description.

Sometimes, we just don't want to use a value of the value type, that is, we want to use a reference. There are many reasons for this. Fortunately, C # And. NET provide a mechanism named boxing, which allows you to create an object based on the value type and then use a reference to the new object. Let's first review two important facts before getting started with the actual example:

1) for a variable of the reference type, its value is always a reference;

2) for a value type variable, its value is always a value of the value type.

Based on these two facts, the following three lines of code do not seem to have much truth at first glance:

Int I = 5;

Object o = I;

Int j = (int) o;

Here, I is a value type variable, and o is a reference type variable. Does it make sense to assign the I value to o? The value of o must be a reference, and the number 5 is not an reference. It is an integer. The actual occurrence is packing: During the runtime, an object containing the value (5) will be created on the stack (it is a common object ). The o value is a reference to the new object. The value of this object is the original value of a copy. Changing the I value does not change the value in the box.

Execute the opposite operation in Row 3-unpack. The compiler must tell the compiler what type the object is to be split. If an error type is used, an InvalidCastException is thrown. Similarly, the value in the box will be copied. After the value is assigned, the relationship between j and the object will no longer exist.

In fact, the above paragraph is a simple and clear explanation of packing and unpacking. The only problem left is that you need to know when the packing and unpacking will happen. Unpacking is usually obvious, because a forced type conversion should be explicitly displayed in the code. Packing may occur when you are not aware of it. The above shows a simple version. However, if the ToString, Equals, or GetHashCode method is called for a value of the type, it is also boxed if the type does not overwrite these methods. In addition, when a value is used as an interface expression-assign it to an interface type variable, or pass it as an interface type parameter-it will also be boxed. For example, the IComparable x = 5 Statement will pack the number 5.

Pay attention to packing and unpacking because they may reduce performance. The overhead of one packing and unpacking operation is negligible, but if you perform thousands or hundreds of such operations, it will not only increase the overhead of the operation of the program itself, but also create a large number of objects, these objects will increase the burden on the garbage collector. Similarly, this kind of performance loss is usually not a big problem, but it should be noted.

Here, we will briefly introduce the value type and reference type, packing and unpacking operations, and briefly introduce delegation in the previous section. I hope to help you.
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.