. NET face question 01-value type and reference type

Source: Internet
Author: User

Common Interview Topics:

1. What is the difference between a value type and a reference type?

2. What are the differences between structure and class?

3. Delegate is a reference type or a value type? enum, int[] and string?

4. What is the difference between heap and stack?

5. Under what circumstances will data be allocated on the heap (stack)? Do they have a difference in performance?

6. Can the "structure" object be allocated on the heap? What happens and what needs attention?

7. Understand that parameters are passed by value? and pass by reference?

8. out and ref the difference with the same point?

9. What predefined value types are supported in C #? What predefined reference types are supported in C #?

10. Are there several ways to determine value types and reference types?

11. Say the life cycle of value types and reference types?

12. If a reference type is defined in the struct, how is the object stored in memory? For example, does the class user object in the following struct be stored on a stack or on a heap?

 public struct mystruct {     publicint  Index;       public
Recognize value types and reference types:

Original aim, as long as the principle of value type and reference type are understood, all the above topics are Solved.

Basic concepts

The CLR supports two types: reference types and value types . This is. NET language, they vary from type definition, instance creation, parameter passing, to memory Allocation. Although it seems simple, it does not seem to be a lot of people who really understand its meaning.

Picture references

The show was clear. NET type classification, value types are mainly simple, basic data types, reference types are mainly used for richer, complex, composite Data types.

Memory structure

The most fundamental difference between a value type and a reference type is the difference in memory allocation, before which you first understand two important concepts in memory of the Clr:

Stack stack : line stacks, managed by the operating system, holds value types, reference type variables (that is, addresses that refer to objects on the managed Heap). The stack is thread-based, which means that a thread will contain a line stacks, and the value type of the line stacks will be cleaned up at the end of the object scope and is highly efficient.

GC Heap Managed heap : the memory space that is partitioned on the process address space after the process is initialized, Stored. NET runs, All reference types are allocated on the managed heap , and the objects allocated on the managed heap are managed and freed by the GC. The managed heap is process-based and of course there are other more complex structures within the managed heap that are interesting to understand.

In conjunction with understanding, the variable A and its value 3 are stored on top of the STACK. Variable b is stored on the stack, whose value points to the address of the managed heap object of the string "123" (the string is a reference type and the string object is stored on top of the managed Heap.) The string is a special reference type, which is discussed later in this Article) "

Is the value type always stored on top of the stack? Are all reference types stored on top of the managed heap?

1. Individual value type variables, such as local value type variables, are stored on the stack;

2. When the value type is a field or property of a custom class, it is stored on the managed heap with the reference type, at which point she is part of the reference type;

4. All reference types must be stored on the managed heap.

5. In another case, the reference type field is defined with the above topic 12, the struct (value type), the struct is stored on the stack, its reference Variable field stores only the memory address, and points to the reference instance in the Heap. Delivery of objects

Assigning a variable of a value type to another variable (or passing as a parameter) performs a one-time value copy. Assigning a variable of a reference type to a variable of another reference type, the value copied is the memory address of the reference object, so that multiple variables point to the same reference object instance when the value is assigned . It is important to understand this, and the following code tests to Verify:

intV1 =0; intV2 =v1; V2= -; Console.WriteLine ("v1="+ v1);//output: v1=0Console.WriteLine ("v2="+ v2);//output: v2=100User U1=NewUser (); u1. age=0; User U2=u1; u2. age= -; Console.WriteLine ("u1. Age="+ u1. age);//output: u1. age=100Console.WriteLine ("u2. Age="+ u2. age);//output: u2. Age=100 because u1/u2 points to the same object

When the object is passed as a parameter, the effect is the same as above, they are all called by value, but because of the difference between the value type and the reference type, it produces different effects.

Parameters-passed by Value:
Private voidDotest (intA) {a*=2; }        Private voiddousertest (user user) {user. age*=2; } [NUnit.Framework.Test] public voiddoparatest () {intA =Ten;            Dotest (a); Console.WriteLine ("a="+ a);//output: a=10User User =NewUser (); User. age=Ten;            Dousertest (user); Console.WriteLine ("User. Age="+ User. age);//output: User. Age=20}

The above code example, the parameters of two methods, are passed by value

    • For a value type (int a): A copy of the value of the variable A is passed, so the original a value does not change.
    • For reference types (user user): a copy of the reference address of the variable user (the memory address of the user object Instance) is passed, so they operate on the same user object Instance.
Parameters-passed by Reference:

The two main keywords that are passed by Reference: out and ref regardless of value type or reference type, the effect of passing by reference is the same, without passing a copy of the value, but referring to a reference (a pointer like a C + + pointer). outand ref It is important to understand this by telling the compiler that the pass amount is the parameter address, not the parameter itself.

The code is simple to test, if you replace the out effect is the same

Private voidDotest (ref intA) {a*=2; }        Private voidDousertest (refUser User) {user. age*=2; } [NUnit.Framework.Test] public voiddoparatest () {intA =Ten; Dotest (refa); Console.WriteLine ("a="+ a);//output: a=20, The value of a has changedUser User =NewUser (); User. age=Ten; Dousertest (refuser); Console.WriteLine ("User. Age="+ User. age);//output: User. Age=20}

out and ref the main similarities and differences :

    • outand ref both instruct the compiler to pass the parameter address, which is the same behavior;
    • Their use mechanism is slightly different, ref requires parameters to be explicitly initialized before use, out to initialize within the method;
    • outAnd ref can not be overloaded, that is, can not define method (ref int A) and method (out int a) Such overloads, from the compilation point of view, the essence of the two are the same, but the use of the difference;
Problems

Answer to the Question: 1. What is the difference between a value type and a reference type?

Value types include simple types, struct types, and enumeration types, and reference types include custom classes, arrays, interfaces, delegates, and so On.

    • 1, Assignment: When you assign a value type variable to another value type variable, the contained value is Copied. This is different from the assignment of a reference type variable, where the assignment of a reference type variable copies only the reference to the object (that is, the memory address, like a pointer in C + +), without copying the object itself.
    • 2. Inheritance: value types cannot derive new types, all value types are implicitly derived from System.valuetype. But as with reference types, structs can also implement Interfaces.
    • 3. Null: Unlike reference types, value types cannot contain null Values. however, nullable types allow NULL to be assigned to a value type (he is actually a syntactic form, with special handling at the Clr's bottom).
    • 4, Each value type has an implicit default constructor to initialize the default value of the type, the value type initially defaults to 0, and the reference type defaults to Null.
    • 5. Value types are stored in the stack, and reference types are stored in the managed heap.
2. What are the differences between structure and class?

Structs are value types, classes are reference types, and the main difference is title 1. The other difference:

    • The structure does not support the Non-tragic constructor, does not support the destructor, and cannot have protected decoration;
    • Structures are often used for data storage, and class classes are used for behavior;
    • Class needs to instantiate the object with the new keyword, and the struct may not apply the new keyword;
    • Class can be abstract, struct does not support abstraction;
3. Delegate is a reference type or a value type? enum, int[] and string?

Enum enumerations are value types, others are reference types.

4. What is the difference between heap and stack?
Thread stacks: Short Stack stack managed heap: simply heap heap
    • Most of the value types are allocated on the stack, and the reference types are allocated on the heap;
    • Stacks are managed by the operating system, and the variables on the stack are freed after their scope is completed, but with limited space. The heap is controlled by the Clr's gc;
    • The stack is thread-based, with each thread having its own line stacks, with an initial size of 1M. The heap is process-based, a process allocates a heap, and the size of the heap is dynamically controlled by the GC according to the operating conditions;
6. Can the "structure" object be allocated on the heap? What happens and what needs attention?

A struct is a value type, and two cases are assigned to the Above:

    • A structure as a field or attribute of class that is assigned to the heap along with the class;
    • After boxing will be stored in the heap, as far as possible to avoid the value type of boxing, value types of unboxing and boxing have a performance loss, the next one will focus on;
7. Understand that parameters are passed by value? and pass by reference?
    • Pass by value: A copy of the value that the value type passes, and the reference type passes the memory address of the reference variable, and they still point to the same object.
    • Pass by reference: the memory address of the parameter is passed by keyword out and ref, and the effect of the value type and reference type is the Same.
8. outAnd refThe difference with the same point?
    • outand ref both instruct the compiler to pass the parameter address, which is the same behavior;
    • Their use mechanism is slightly different, ref requires parameters to be explicitly initialized before use, out to initialize within the method;
    • outAnd ref can not be overloaded, that is, can not define method (ref int A) and method (out int a) Such overloads, from the compilation point of view, the essence of the two are the same, but the use of the difference;
9. What predefined value types are supported in C #? What predefined reference types are supported in C #?

Value types: integers, floating-point numbers, characters, bool, and decimal

Reference Type: object,string

10. Are there several ways to determine value types and reference types?

Simply put, the inherited from System.ValueType is a value type, whereas a reference type.

11. Say the life cycle of value types and reference types?

The value type is disposed after the scope ends.

The reference type is reclaimed by the GC garbage collection Period. The answer may be too simple, and a more detailed answer will be in a later Article.

12. If a reference type is defined in the struct, how is the object stored in memory? For example, does the class user object in the following struct be stored on a stack or on a heap?
 public struct mystruct {     publicint  Index;       public User user;}

MyStruct is stored in the stack, and the instance of its field user is stored in the heap, and the Mystruct.user field stores the memory address that points to the user Object.

All Rights reserved, article source: http://www.cnblogs.com/anding

Personal ability is limited, the content of this article is only for study, discussion, welcome correction, Exchange.

. NET interview analysis (00)-opening to talk about the interview & Series Articles index

Resources:

Value type and Reference type explained:http://www.tuicool.com/articles/mbufa3u

C # Value types and reference types (top): http://www.cnblogs.com/siqing99/archive/2012/04/03/2430918.html

Books: CLR via C #

Books: The. NET You must know

. NET face question 01-value type and reference type

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.