Differences between csharp class, reference class, structure, and value type (struct)

Source: Internet
Author: User

The location where data is stored in the memory depends on its data type. in C #, it is divided into value type and reference type. Value Type data is stored in the memory stack, each variable or program has its own stack. It cannot share a stack address. When a data value type variable is passed to another variable of the same type, two different addresses are allocated in the stack.

Data of the reference type is stored in the heap in the memory. Different variables or programs can use the data at the same position together. When data is transferred from a reference type variable to another variable of the same type, the reference address of the variable is passed to the new variable, and the data stored in the current heap is referenced.

You can draw a detailed conclusion through the example:

Using System; using System. collections. generic; using System. linq; using System. text; // defines a rectangle class. The class belongs to the reference class RefRectangle {public int width; public int height;} // defines a rectangle structure 1, belong to the value type struct ValRectangle {public int width; public int height;} class RefValRectangle {public static void Main () {// create a rectangle object, and pass the value to another object RefRectangle ref1 = new RefRectangle (); ref1.width = 3; ref1.height = 4; RefRectangle ref3 = ref1; Console. writeLine ("Dimensions of ref1 are:" + ref3.width. toString () + "... "+ ref3.height. toString (); Console. writeLine ("Change Dimensions of ref1"); ref1.width = 10; ref1.height = 50; bool bTransfer = ref3.Equals (ref1); Console. writeLine ("Dimensions of ref1 now:" + ref3.width. toString () + "..... "+ ref3.height. toString (); Console. writeLine (bTransfer. toString (); Console. readLine (); // create a rectangle object and pass the value to a new rectangle structure ValRectangle val1 = new ValRectangle (); val1.width = 3; val1.height = 4; valRectangle val3 = val1; Console. writeLine ("Dimensions of val1 are:" + val3.width. toString () + "... "+ val3.height. toString (); Console. writeLine ("Change Dimensions of val1"); val1.width = 10; val1.height = 50; bool bPass = val3.Equals (val1); Console. writeLine ("Dimensions of val1 now:" + val3.width. toString () + "..... "+ val3.height. toString (); Console. writeLine (bPass. toString (); Console. readLine ();}}Conclusion:

Output result:

Dimensions of ref1 are : 3...4Change Dimensions of ref1Dimensions of ref1 now are : 10.....50TrueDimensions of val1 are : 3...4Change Dimensions of val1Dimensions of val1 now are : 3.....4False

When the ref (reference type) variable is passed, the first variable is changed, and the second variable is changed because the two variables reference the content of an address in the heap at the same time. When a variable changes, corresponding to the heap in the memory also changes, and another variable also changes.

When the val (Value Type) variable is passed, changing the first variable does not affect the value of the second variable. This is because when the variable is passed, an address is assigned to the new variable in the stack, so the two variables are no longer related after the transfer.

Differences between classes and structures

C # contains two types of data: value data and reference data.

First, let's talk about what types are value types, such as basic types such as int, float, and bool, And the types defined by struct, such as DateTime. In addition, strings, arrays, and class-defined types are all reference types. The comparison is as follows:

  Value Type Reference Type
Memory Allocation location Allocated in stack Allocated in heap
Efficiency High efficiency, no need for address translation Low Efficiency, requiring address translation
Memory reclaim Recycle immediately after use After use, do not recycle immediately, wait for GC to recycle
Assignment operation To create a new object with the same value. Only references the original object.
Function parameters and return values Is copying objects Is the reference of the original object and does not produce new objects
Type Extension Not easy to expand Easy to expand, convenient and Type Extension

Value Type and reference type

Structure is value type: value type is allocated to the stack. All base types are structure types. For example, int corresponds to System. int32 structure. string corresponds to system. string Structure. You can create more value types by using the structure.
Class is a reference type: the reference type is allocated on the stack.
The execution efficiency of stacks is higher than the execution efficiency of stacks. However, the stack resources are limited and it is not suitable for processing large logical and complex objects. Therefore, structure processing is a small object to be treated as a base type, while classes process a certain business logic.
Because the structure is a value type, a value can be assigned between structures to create a new structure, while a class is a reference type. A value assignment between classes is just a copy reference.

Note:
1. Although the structure is different from the class type, their base types are all objects. in c #, all types of base types are objects.
2. although the New operator is used for structure initialization, the structure object is still allocated on the stack instead of the stack. If the new operator is not used, before all fields are initialized, the field remains unassigned and the object is unavailable.
3. Inheritance
Structure: It cannot be inherited from another structure or class. Although the structure is not explicitly declared using sealed, the structure is implicit sealed.
Class: Completely scalable. Unless the declared sealed is displayed, the class can inherit other classes and interfaces, and its own can also be inherited.
Note: although the structure cannot be inherited, the structure can inherit interfaces, and methods are the same as class inheritance interfaces.

4. Internal Structure:
Structure: No default constructor, but you can add constructor without destructor
No abstract and sealed (because it cannot be inherited) cannot have the protected Modifier
It is incorrect to initialize the instance field in the structure without using new initialization.
Class: There are default constructor; destructor: abstract and sealed can be used.
The protected modifier must be initialized using new.

How to Select structure or Class

After discussing the similarities and differences between structures and classes, we will discuss how to choose a structure or a class:
1. The stack space is limited. For a large number of logical objects, creating classes is better than creating structures.
2. structure indicates lightweight objects such as dots, rectangles, and colors. For example, if an array containing 1000 vertex objects is declared, additional memory will be allocated to each referenced object. In this case, the structure cost is low.
3. Classes are the best choice for presentation of abstract and multi-level object Layers
4. In most cases, this type is the best choice for structure when it is only some data.

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/Terminatorss/archive/2009/08/04/4405997.aspx

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.