Structure and class

Source: Internet
Author: User
Tags abstract constructor modifiers
In C + +, structs and classes are similar, and the members of structs default to public types, and the members of the classes default to private types. In C #, they are completely different types:

1: Type:

Structs are value types, and addresses are allocated on the stack, so assignments between structs can create new structures, while classes are reference types, and addresses are assigned on the heap, so assignments between classes are just replication references. The execution efficiency of the stack is more efficient than that of the heap, but the stack has limited resources and is not suitable for dealing with large logically complex objects, so the struct handles the small object treated as the base type, while the class handles a business logic.

2: Inheritance:

Structs cannot be inherited except that they are derived from System.ValueType. But structs can inherit interfaces, and methods and classes inherit interfaces. A class can be derived from a base class and can derive any number of interfaces.

3. Internal structure:

Structure:

Provides a parameterless default constructor and does not allow substitution, but you can add a parameter constructor.

No destructor

No virtual, abstract, and sealed (because it cannot be inherited)

Cannot have protected modifiers

Initializing an instance field in a struct is an error

Class:

There is a default constructor

There is a destructor

You can use virtural, abstract, and sealed

There are protected modifiers

Instance fields can be initialized

4: Structure can specify how fields are laid out in memory



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.