Quick Start C # comparison between struct and class

Source: Internet
Author: User

1. The following is a structure definition:

Public struct Point {public int X {get; set;} public int Y {get; set ;}}

When to use the structure:

The values in a small data structure are generally not modified.
2. Class Definition:
Public class Animal {public string Name {get; set;} public double Weight {get; private set;} private string _ color; public string Color {get {return _ color ;} set {_ color = value ;}} public void MakeSound () {Console. writeLine (Sound );}}

3. The difference between the structure and the class: no explicit constructor is available in the above two cases. If you add an explicit constructor to them:
Public struct Point {public int X {get; set;} public int Y {get; set;} public Point (int X, int Y) {this. X = X; this. Y = Y ;}}

If we instantiate it, we can find that the implicit constructor is still available:
Point p = new Point (); Point P = new Point (10, 12 );

At the same time, we cannot define a non-parameter constructor in the structure. For classes, if we do not write any constructor for the class, the C # compiler automatically generates a non-parameter constructor for the class during compilation, but once we write any constructor for this class, this implicit constructor will not be automatically generated.

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.