1. The biggest difference
The variable defined by the struct type is the value type, and the variable defined by the class is the reference type. Therefore, the objects defined by the struct type are allocated on the stack, while the objects defined by the class are allocated on the heap.
Members cannot be declared as protected.
For example:
struct Test1 { protected readonly bool c;//There will be an error}
Is the implicit sealed class
Therefore, struct cannot be inherited or inherited, so its members cannot be designated as abstract or virtual (after all, they are sealed, and virtual and abstract functions cannot be implemented).
But struct can implement interfaces.
interface i1 { void fun(); } struct Test1:i1 { public void fun() { throw new (); } }
The default constructor cannot be overloaded
struct Test1 { public int a ; public Test1(int A) //But non-default constructors can be defined { a = A; } public Test1()//Overload the default constructor and an error will be reported { a = 1; } }
5. Regarding the initialization of the object
1) Variables in a structure cannot be assigned initial values directly in the structure, and variable members of the class can.
struct Test1 { public int a =1;//The initial value is not allowed, so it is wrong public int b;//Yes } class Test2 { public int a=1;//Yes public int b;//Yes, the default initial value is 0}
2) When creating a structure object using the New operator, the appropriate constructor will be called to create the structure. Unlike classes, structures can be instantiated without using the New operator. (That is, not using new also really opens up a space to store the struct variable)
3) However, if the New operator is not used, the field is assigned and the object is used only after all fields are initialized. If you use the default constructor for new, the data will be assigned by default (int is 0, reference type is Null)
struct Test1 { public int a =1; public string b =1; } void TestFun() { Test1 test1; = 1, = "1234";//You must assign values to both a and b to use test1 (); Test1 test2=new Test1();//=0,=Null }
4) The constructor in struct must assign initial values to all data members.
struct Test1 { public int a ;//The initial value is not allowed, so it is wrong public string b; public Test1(int A) { a = A; b = "4534";//Abstract value must be assigned to all data members, otherwise an error will be reported } }
6. The structure has no destructor, and it is impossible to define a destructor for the structure by itself.
After all, struct is a value type, and it is useless to use destructors.
struct Test1 { ~Test1() { }//Wrong practice will report an error}
This is the end of this article about the details of the difference between struct and class in C#. For more related contents of C# struct and class, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!