Directory
Comparison of instances between classes and structs
The difference between class and structure
How to select a structure or class
A Example comparison of classes and structs:
Structure Example:
public struct Person
{
string Name;
int height;
int weight
public bool overWeight()
{
//implement something
}
}
class Example:
public class TestTime
{
int hours;
int minutes;
int seconds;
public void passtime()
{
//implementation of behavior
}
}
Call Procedure:
public class Test
{
public static ovid Main
{
Person Myperson=new Person //声明结构
TestTime Mytime=New TestTime //声明类
}
}
As we can see from the example above, the declaration of a class is very similar to that of a struct, except that the qualifier is the difference between struct and class, and the method of defining a new structure and defining a new class is very similar when used. So what is the specific difference between a class and a structure?
Two. Differences in class and structure
1. Value type and reference type
Structs are value types: value types assign addresses on the stack, all base types are struct types, for example: int corresponds to SYSTEM.INT32 structure, string corresponds to System.String structure, you can create more value types by using structs
Class is a reference type: A reference type assigns an address on the heap
The execution efficiency of the stack is higher than that of the heap, but the stack has limited resources and is not suitable for dealing with large logically complex objects. So the struct handles a small object treated as a base type, while a class handles a business logic
Because structs are value types, assignments between structs can create new structures, while classes are reference types, and assignments between classes are just copies of references