1,class is a reference type, structs is a value type
Since class is a reference type, class can be set to null. However, we cannot set the struct to null because it is a value type.
struct ASTRUCT
{
int afield;
}
Class AClass
{
int afield;
}
Class MainClass
{
public static void Main ()
{
AClass B = null; No error.
Astruct s = null; Error [cannot convert null to ' astruct ' because it is a value type].
}
}
2, when you instantiate a class, it will be created on the heap. While you instantiate a struct, it will be created on the stack
3, you are using a reference to the class instance. And you're not using a reference to a struct. (instead of using them directly)
4, when we pass class as a parameter to a method, we are passing a reference. A struct passes a value rather than a reference.
5,structs can not have initializers, class can have initializers.
Class MyClass
{
int myVar = 10; No syntax error.
public void Myfun ()
{//statements}
}
struct MYSTRUCT
{
int myVar = 10; Syntax error.
public void Myfun ()
{//statements}
}
6,classes can have an obvious parameterless constructor, but the struct can not
Class MyClass
{
int myVar = 10;
Public MyClass ()//no syntax error.
{
Statements
}
}
struct MYSTRUCT
{
int MyVar;
Public mystruct ()//syntax error.
{
Statements
}
}
7, the class must be instantiated with the new keyword before it is used, and the struct does not need
MyClass Aclassobj; MyClass aclassobj=new MyClass (); is the correct format.aclassobj.
Myvar=100;//nullreferenceexception (because Aclassobj does not contain a reference to an object of type MyClass).
MyStruct Astructobj;
astructobj.myvar=100; No exception.
8,class supports inheritance and polymorphism, and struct does not support. Note: But structs can implement interfaces like classes
9, since the struct does not support inheritance, its members cannot be decorated with protected or protected Internal
The 10,class constructor does not need to initialize all fields, and the constructor of the struct must initialize all fields
Class MyClass//no error (No matter whether the Field ' myclass.mystring ' is initialized or not).
{
int myInt;
String myString;
Public MyClass (int aInt)
{myInt = aInt; }
}
struct MyStruct//Error (Field ' mystruct.mystring ' must be fully assigned before it leaves the constructor).
{
int myInt;
String myString;
Public mystruct (int aInt)
{
MyInt = aInt;
}
}
11,class can define the destructor, but the struct can not
12,class is more suitable for large and complex data, and structs are suitable for new types that are combined as some of the data that is often used.
Application: struct has a performance advantage, class has an object-oriented expansion advantage.
The type used for the underlying data store is designed as a struct type, and the type used to define the application behavior is designed as class. You should use class if you are unsure of the future application of the type.
The difference between struct and class in C #