.NET interview preparation (four)-primitive type value type reference type

One, primitive type

  • Data types directly supported by the compiler
  • Primitive types directly map to types existing in FCL (Framework Class Library)
  • Example: int of c# is mapped to System.Int32

Two, reference type and value type

1. Value type

Q: Why are there value types?
A: Reference types are always allocated from the managed heap. If all types are reference types, the performance of the application will be significantly reduced, so CLR provides a lightweight type: value type.

  • Instances of value types are generally allocated on the thread stack
  • The value type variable directly contains its data, does not need a pointer to the instance, and is not controlled by CG

Value types mainly include two types: structure and enumeration :

  1. Numerical type
  2. bool type
  3. char type
  4. User-defined structure

Characteristics of value types :

  1. Are derived directly or indirectly from System.ValueType
  2. The value type is implicitly sealed and can neither be derived nor inherited, in order to prevent the value type from being used as the base type of other reference types
  3. Each value type has a default constructor to initialize the default value

When is it appropriate to set the type as a value type

  • Types have the behavior of primitive types.
  • Types do not need to be inherited or derived
  • The instance field of the type is small (16 bytes or less)
  • The instance of the type is larger, but it is not passed as a method argument or returned from the method

The difference between value types and reference types:

  • There are two representations for value type objects: unboxed and boxed; reference types are always in boxed form
  • Since value types cannot be used as base types to define new value types and reference types, no new virtual methods should be introduced in value types
  • Assigning a value type variable to another value type variable will perform a field-by-field copy. Assigning a reference type variable to another reference type variable only copies the memory address

Parameters—passed by reference type :

out and ref,

  • Instruct the compiler to pass the parameter address
  • ref requires parameters to be explicitly initialized before use, and out to be initialized in method memory
  • Neither out nor ref can be overloaded

Insert picture description here

Three, dynamic primitive type

The program needs to process some information that is only known at runtime.
After dynamic compilation, it is an object type. Type checking is not performed during compilation, and type checking is put into runtime

Guess you like

Origin blog.csdn.net/hhhhhhenrik/article/details/93655892