C# analysis of the difference between structure and class

Abstract: Explain the difference between structure and class with specific examples one by one, and analyze the application of the two.

Programming language: C#

Programming environment: Visual Studio 2019

Table of contents

the difference

summary

each message


the difference

  • Define the structure with struct and define the class with class.
  • Structs are value types and classes are reference types. (This is the root cause of all the differences between the two)
  • When declaring a structure, its members cannot be assigned a value, while when declaring a class, its members can be assigned a value.

  •  The constructor of the structure must assign values ​​to all members, and no parameter constructor is allowed, while the constructor of the class does not have these restrictions.

  • Structs can be instantiated without new, but classes must be instantiated with new.

  •  When traversing a structure array or list, it is not allowed to modify its iteration variable members, but the class can. (When I encountered this problem for the first time when programming, I thought about it for a long time before I deeply understood the difference between structures and classes)

summary

        After understanding the difference between the two, the editor came to the following conclusions. The structure is actually a lightweight version of the class. Because it is a value type, its allocation and release are relatively convenient, but it is sealed, immutable, and logically represents a single value. It is impossible to use two variables to contain references to the same object , and cannot directly modify a member value of a structure array or list, it needs to be modified in units of the entire structure. On the contrary, classes are reference types, which are more flexible to use and have more advantages, but the cost of memory allocation and release is greater.

        This article is only a brief analysis of the difference between the two. If you want to better understand the difference and connection between the two, you need to understand the difference and connection between value types and reference types in a deeper level. You can refer to my other article. —— (1 message) C# analysis of value type and reference type, heap memory and stack memory, shallow copy and deep copy_C# is actually not difficult blog-CSDN blog

each message

        Every setback or unfavorable mutation carries an equally or greater favorable seed.

 

Guess you like

Origin blog.csdn.net/lucgh/article/details/130394720