The difference between Struct and Class in C # and their applicability

Source: Internet
Author: User

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 ;//
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.