First difference, the source of the original http://www.dotnetspider.com/resources/740-Difference-between-class-struct-C.aspx
1. class is the reference type, and structs is the value type.
Since the class is a reference type, the class can be set to null. However, we cannot set 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 instance a class, it will be created on the stack. And your instance has a struct, which will be created on the stack.
3. You are using a reference to the class instance. Instead of referencing a struct. (Instead, use them directly)
4. When we pass the class as a parameter to a method, we pass a reference. Struct passes a value rather than a reference.
5. structs cannot have an initializer, and class can have an initializer.
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 a non-parameter constructor, but Struct cannot.
Class MyClass
{
Int myVar = 10;
Public MyClass () // no syntax error.
{
// Statements
}
}
Struct MyStruct
{
Int myVar;
Public MyStruct () // syntax error.
{
// Statements
}
}
Class 7 must be instantiated with the new Keyword before use, and Struct does not need
MyClass aClassObj ;//