.NET basics (01) - value types and reference types

  Common interview questions:

1. The value types and reference types difference?

2. The difference between the structure and the like?

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

4. The difference between stack and heap?

Data will be allocated on the heap (stack) 5. Under what circumstances? They do have a difference in performance?

6. "structure" may be allocated on the heap objects it? Under what circumstances would happen, what needs to pay attention to it?

7. understand the argument is passed by value? And pass-by-reference?

8. outand refthe difference between the same point?

9. C # which supports several predefined value types? C # which supports predefined reference types?

10. There are several ways determination value and reference type?

11. Talk about value types and reference types of life cycle?

12. If the definition of the structure reference types, object in memory is how to store? For example, the following structure of the object class User class is stored on the stack or heap?

public struct MyStruct 
{ 
    public int Index; 
    public User User; 
}

  Understanding value types and reference types

Remain the same, as long as the clear value types and reference types in principle, subject to all of the above have been solved.

basic concept

CLR supports two types: reference types and value types . This is the basis and key .NET language, they, create an instance of the type definitions, parameters are passed to the memory allocation are different. Although it seems simple, but really understand its meaning seems not many people have.

Picture references

The following figure shows clearly the .NET type of classification, the value of the main types are simple, basic data type, a reference type is mainly used for a richer, complicated, complex data types.

Memory Architecture

Its memory allocation is the difference difference between value types and reference types most causes of, before we must first understand the CLR memory in two important concepts:

Stack Stack : thread stack, operating system management, storage of value type reference type variable (the address is a reference to an object in the managed heap) . Stack is thread-based, which means that a thread will contain a thread stack, thread stack value type will be cleaned at the end of the subject scope, efficiency is very high.

GC Heap managed heap : After the initialization process is divided in the process address space memory space, the process of storing objects in the .NET runtime, all reference types are allocated on the managed heap , the managed heap allocated objects are managed by the GC and release. Managed heap is process-based, of course, there are other managed heap more complex internal structure, are interested can understand.

Understood in conjunction with the FIG., The value of the variable a and 3 are stored on the stack top. The variable b is stored on the stack, which points to a string value "123" address managed heap objects (character string is a reference type, the string is stored in the managed heap objects above. Reference string is a special type, later in the article will specifically Discussion) "

image

Value types have been stored on the stack on top of it? All reference types are stored in the managed heap on top of it?

1. The individual values ​​of a variable type, such as the type of the local variable values ​​are stored in the stack above;

2. When the value of type is a custom class field attribute, it is stored with reference to the type of managed heap, when she is part of a reference type;

4. All reference types are certainly stored in the managed heap.

5. In another case, the subject with the above 12, define a reference type field (Type value) in the structure, the structure is stored on the stack, which reference variable field stores only the memory address, pointing to a reference example of the heap.

Passing objects

Assigning a value type variable to another variable (or passed as a parameter), performs a replication value. The reference type variable to another variable of reference type, it copies the value of the memory address referenced object, and therefore will be assigned after a plurality of variable reference point to the same object instance. It is important to understand the following code to test to test:

int v1 = 0;
            int v2 = v1;
            v2 = 100;
            Console.WriteLine("v1=" + v1); //输出:v1=0
            Console.WriteLine("v2=" + v2); //输出:v2=100

            User u1=new User();
            u1.Age = 0;
            User u2 = u1;
            u2.Age = 100;
            Console.WriteLine("u1.Age=" + u1.Age); //输出:u1.Age=100
            Console.WriteLine("u2.Age=" + u2.Age); //输出:u2.Age=100,因为u1/u2指向同一个对象

When the object is passed as a parameter, the same effect as above, they are passed by value referred to, but because of the difference value and reference types, which leads to an effect is also different.

Parameter - passed by value:


private void DoTest(int a)
        {
            a *= 2;
        }

        private void DoUserTest(User user)
        {
            user.Age *= 2;
        }

        [NUnit.Framework.Test]
        public void DoParaTest()
        {
            int a = 10;
            DoTest(a);
            Console.WriteLine("a=" + a); //输出:a=10
            User user = new User();
            user.Age = 10;
            DoUserTest(user);
            Console.WriteLine("user.Age=" + user.Age); //输出:user.Age=20
        }

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

  • For value type (int a): the value is passed a copy of the variable copy, so a value of the original has not changed.
  • For reference types (User user): a user variable transmission Copies reference address (memory address User object instance), and therefore their operations are the same User object instance.

Parameters - passed by reference:

According to two main keywords passed by reference: outand refregardless of the value type or reference type, press the effect is the same as passed by reference, not a copy of the transfer value, but cited references (similar to c ++ pointers pointer). outAnd reftells the compiler that the method parameter is passed forehead address instead of the parameters itself, it is important to understand.

Code simple test, if replaced out effect is the same

private void DoTest( ref int a)
        {
            a *= 2;
        }

        private void DoUserTest(ref User user)
        {
            user.Age *= 2;
        }

        [NUnit.Framework.Test]
        public void DoParaTest()
        {
            int a = 10;
            DoTest(ref a);
            Console.WriteLine("a=" + a); //输出:a=20 ,a的值改变了
            User user = new User();
            user.Age = 10;
            DoUserTest(ref user);
            Console.WriteLine("user.Age=" + user.Age); //输出:user.Age=20
        }

outAnd refthe major similarities and differences :

  • outAnd refboth parameters indicating compiler passes the address, in the same behavior;
  • Their use slightly different mechanisms, ref parameters required to be explicitly initialized before use, out internally to initialize method;
  • outAnd refnot overloaded, it is not defined in Method (ref int a) and Method (out int a) such overloads from the compiler perspective, both the substance is the same, but are different when used;

 

 Topic Answer Analysis:

1. The value types and reference types difference?

Value types include simple types, a structure and enumerated types, including custom class reference types, arrays, interfaces, delegates, and the like.

  • 1, the assignment mode: When a value assigned to another type of variable type variable value, the value contained in the copy. This is different from a reference type variable assignment, the assignment referencing only type variable reference copy target (i.e. memory address pointers in C ++ - like), without copying the object itself.
  • 2, Inheritance: Value Type impossible to derive new types, all value types are implicitly derived from System.ValueType. However, the same reference type that the structure of the interface may be implemented.
  • 3, null: the reference types, value types can not contain a null value. However, empty types allow null values ​​assigned to type (he is only a grammatical form in the bottom clr made special treatment).
  • 4, the value of each type has an implicit default constructor initializes the default value for that type, the type of the initial value will default to 0, the default reference type is null.
  • 5, the type of the value stored in the stack, referenced type managed heap memory.

2. The difference between the structure and the like?

Structure is a value type, class is a reference type, the main difference as a title. Other differences:

  • Structure does not support a miserable constructor, destructor is not supported and can not be protected with a modification;
  • Used in the data storage structure, a multi-class class behavior;
  • requires using new instance of class objects, struct can not apply the new keyword;
  • class may be an abstract class, struct does not support the abstract;

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

enum enumeration is a value type, others are reference types.

4. The difference between stack and heap?

Thread Stack: Stack Stack referred to 
the managed heap: Heap Heap short
  • Most value types allocated on the stack, reference types are allocated on the heap;
  • Stack is released by the operating system, variables on the stack after the completion of its scope, high efficiency, but space is limited. GC controlled by the CLR stack;
  • Stack is based, each thread has its own thread stack of the thread, the initial size of 1M. Is based on the process stack, a process of allocating a heap, the heap size dynamically controlled in accordance with the operation from the GC;

6. "structure" may be allocated on the heap objects it? Under what circumstances would happen, what needs to pay attention to it?

Is a value type structure, there are two cases to be partitioned above:

  • As the structure of a field or attribute class, the class would be allocated along with the top of a pile;
  • After packing will heap memory, try to avoid value type of packing, unpacking and packing of value types have performance loss, the next will focus on;

7. understand the argument is passed by value? And pass-by-reference?

  • Passed by value: For a copy of a copy of its value delivered value types, and reference types passed variable is referenced memory address, the same object they point to.
  • Passed by reference: passing parameters through memory address and keywords out ref, and a reference value type is the same type of effect.

8. outand refthe difference between the same point?

  • outAnd refboth parameters indicating compiler passes the address, in the same behavior;
  • Their use slightly different mechanisms, ref parameters required to be explicitly initialized before use, out internally to initialize method;
  • outAnd refnot overloaded, it is not defined in Method (ref int a) and Method (out int a) such overloads from the compiler perspective, both the substance is the same, but are different when used;

9. C # which supports several predefined value types? C # which supports predefined reference types?

Value types: integer, float, character, bool and decimal

Reference types: Object, String

10. There are several ways determination value and reference type?

In simple terms, inherited from System.ValueType is a value type, on the contrary is a reference type.

11. Talk about value types and reference types of life cycle?

Value Type released after the end of the scope.

Reference types recovered from the GC garbage payback period. The answer may be too simple, more detailed answer in a later article will talk.

12. If the definition of the structure reference types, object in memory is how to store? For example, the following structure of the object class User class is stored on the stack or heap?

public struct MyStruct 
{ 
    public int Index; 
    public User User; 
}

MyStruct stored on the stack, which is stored in the field User examples heap, MyStruct.User field stores the memory address pointing to the User object.

 

Welcome to add a personal Micro Signal: Like if thoughts.

I welcome the attention of the public numbers, not only recommend the latest blog for you, there are more surprises waiting for you and resources! Learn together and common progress!

 

Guess you like

Origin www.cnblogs.com/cool2feel/p/11418636.html