Difference between struct and class in C #
There are several differences:
1. struct is a value type, and class is an object type.
2. struct cannot be inherited, and class can be inherited
3. The default access permission of struct is public, and the default access permission of class is private.
4. struct cannot beProgramThe member declares the constructor. Even the default constructor (without parameters) cannot have the Destructor processing part. This is because the struct constructor is automatically generated by the compiler. The purpose of struct is to describe lightweight objects, such as line and point, with high efficiency.
5. struct's new and class's new are different. Struct's new is to execute the constructor to create a new instance and then copy all fields. While the class allocates a block of memory on the heap and then executes the constructor. The struct memory is not allocated at the time of new, but allocated at the time of definition.
Someone asked why the newguid method in system. guid cannot be inherited. The answer is very simple, because system. GUID is a structure rather than a class.
For example, define the following structures and Classes
Public Struct Mytype
{
Public IntMyinteger;
}
Public Class Class1: mytype
{
}
This sectionCodeWill throw the compilation error content"Class1: cannot inherit from sealed class mytype".
The following code is used:
Public Struct Mytype
{
Public IntMyinteger;
}
Public Struct Class1: mytype
{
}
The compilation error is as follows :"Class1: Type in interface list is not an Interface".
The following are examples provided by Microsoft.
// Copyright (c) 2000 Microsoft Corporation. All rights reserved.
// Struct2.cs
Using System;
Class Theclass
{
Public IntX;
}
Struct Thestruct
{
Public IntX;
}
Class Testclass
{
Public Static Void Structtaker (thestruct S)
{
S. x= 5;
}
Public Static Void Classtaker (theclass C)
{
C. x= 5;
}
Public Static Void Main ()
{
Thestruct = New Thestruct ();
Theclass B = New Theclass ();
A. x = 1 ;
B. x = 1 ;
Structtaker ();
Classtaker (B );
Console. writeline ( " A. X = {0} " , A. X );
Console. writeline ( " B. x = {0} " , B. X );
}
}
The output in this example is:
A. X = 1b. x = 5
From this example, we can see that when a structure is passed to a method, it is only a copy, and when a class is passed, it is a reference. so. X = the output is 1, unchanged, and B. X has changed.
Another difference is that the structure can be instantiated without new, but the class needs. if you do not need new to instantiate a structure, all fields will remain unallocated until all fields are initialized. like a class, the structure can execute interfaces. more importantly, the structure has no inheritance. A structure cannot be inherited from other classes or be the base class of other classes.
From: http://hi.baidu.com/heiru/blog/item/3f20d243e6c9601372f05d5c.html