Differences between struct and classes in C #

Source: Internet
Author: User

I often hear some friends discuss the differences between the structure and class in C #. I have nothing to worry about in the past few days. I hope you can give me some advice.

1. the first is the difference in syntax definition. define a class use the keyword class to define the structure use the keyword struct. in terms of syntax, there are many similarities between classes and structures.

Definition class syntax

 1 class Person 2 { 3    private string name; 4    private int age; 5     6    public void SayHi() 7    { 8        Console.WriteLine("Hello,My Name is "+this.name+",My Age is "+this.age); 9    }10 }

Syntax for defining the structure.

 1     struct Rectangle 2     { 3         private int width; 4         private int height; 5           6         public int GetArea() 7         { 8             return this.width * height; 9         }10     }

In terms of syntax, their syntax is similar. Almost all the members in the class can be defined in struct, except for destructor. Why? The answer is later.

2. Although their syntax is extremely similar, there are several differences in their syntax.

A. fields can be declared in the struct, but the initial values cannot be given when fields are declared.So when we try to write code like this, the C # compiler will prompt a syntax error when compiling the source code into an assembly.

We know that if we declare a field in the class and assign the initial value to this field, it can be dropped, as shown below.

class Person{   private string name ="jack";}

However, if one field is declared and assigned a value for the field, it is as follows.

1 class Person2 {3    private string name;4    name="jack";5 }

 

Therefore, only the members of the class can be defined directly under the class. for example, defining member fields and attribute method constructor. the above code name = "Jack" is called "Execution Code", which means that the Code will be effective only when it is executed. when will the code be executed? When creating class objects? Do you still need Constructors? It is often seen that some beginners directly write such code below the class.

 

However, some people may say that, ah, why can I assign values when declaring fields of the class? The value assignment expression is also an Execution Code? Why is this not an error? Let's take a look at the following code and you will know the truth.

When we use the C # compiler to compile this code into an assembly, let's look at the code that Microsoft has generated for us.

Expand the constructor and see what's wrong with it!

Yes. When the C # compiler is compiling, If we assign values to the field when declaring the field, the C # compiler will put the value assignment code into the constructor during compilation. In fact, strictly speaking, the class field cannot have an initial value. microsoft has helped us with something behind the scenes, but we don't know.

Therefore, no matter in the class and structure, the Execution Code must be written in the method. it cannot be written directly under the structure or class. when the Execution Code is written in the method, the execution time of the code can be determined, that is, the time for this method to be called.

From the above content, we can see that. in essence, fields of the class and structure cannot have initial values. however, in terms of syntax, Microsoft allows us to assign values to class fields. however, Microsoft actually put the Execution Code of the assignment in the constructor for execution. the structure of Microsoft does not help us do this. what is the reason for this. I checked some information and read the articles of other bloggers in the garden. I felt that I could not persuade me, but I couldn't figure out the exact reason why Microsoft would do this. let's put it first. I hope that the children's shoes with the principle will give you some advice.

 

B. constructor.

First, the implicit constructor. we know that in a class, if we do not write any constructor for the class, then the C # compiler automatically generates a parameter-free constructor for this class during compilation. we call this constructor an implicit constructor, but once we write any constructor for this class, this implicit constructor will not be automatically generated.

In the structure, this is not the case. The implicit constructor in the structure exists no matter how. Let's look at the code.

In the following code, we wrote a constructor with parameters for the struct.

We use the new keyword to create the struct object. We found that when calling the constructor, the prompt is that there are two constructor S. One constructor with no parameters is added.

So let's try again, can we manually write a non-parameter constructor? We were so excited that we could give it a try.

The result is Lili's error. So we come to the conclusion.Implicit non-parameter constructor exists in the structure in any case. Therefore, programmers cannot manually add a non-parameter constructor to the structure.

This is not the case with regard to constructors. we know that in the class constructor, we can write any code (provided that it complies with the C # syntax). In the struct constructor, we can also write any code. but C # syntaxIn the struct constructor, you must assign values to all fields of the struct.. Check the following code.

Ah, oh... an error is reported .....

We also know that attributes can be defined in the structure, so we can write it like this when we have kids shoes. See the following code.

This error still prompts that we didn't assign values to all fields in the constructor. This is a problem many kids shoes encounter. Didn't you want to assign values to all fields in the constructor? I have assigned a value now. Why is it still prompted that no value is assigned? In the constructor, we assign values to attributes, and the attributes assign values to fields. Why not? The reason is simple. because the syntax requires us to assign values to all fields, although we can see that assigning values to attributes actually assigns values to fields, we say that attributes are field operations, but is it true? We can do nothing in the Set block of the attribute. If nothing is written, is the attribute still in the operation field? Therefore, attributes are not necessarily in the operation field,In the constructor of the struct, we assign values to attributes instead of assigning values to fields. Therefore, we need to assign values to fields directly in the constructor.

C. Create a struct object.

You can create a struct object without using the new keyword. declare one variable directly. in this case, fields in the struct object do not have an initial value. Therefore, you must assign a value to this field before using the field.

The reason is simple. because the initial value cannot be declared. Although the constructors assign values to the object fields, this method creates a struct object without calling the constructor. Therefore, the programmer must manually assign values before using the constructor. This is the case.

The other method for creating struct objects is the same as that for classes. The new keyword is used to create struct objects. Unlike creating struct objects without the New Keyword, the fields of this struct object already have values. the reason is not hard to understand. The New Keyword calls the constructor, And the struct constructor must assign values to all fields.

Therefore, it is not difficult to guess. what does struct's non-parameter constructor do? assign values to all fields in the non-parameter constructor, assign 0 values to fields of the value type, and assign null values to fields of the reference type.

D.Struct cannot inherit from another structure or class, but it can implement interfaces. special. although the structure cannot be inherited from other classes or structures, all structures are inherited from the valuetype class by default, and the valuetype class inherits from the object class. therefore, struct objects still have super-Class Object members.Let's take a look at the code generated by Microsoft below.

3. The biggest difference between them is that the struct is the value type class and the reference type.

Struct is a value type. When it is used as a local variable, the variable is stored in the stack space, and its object fields are directly stored in this variable, as shown below.

Unlike the reference type class, the reference type variables store the address of the object in the heap space, so when we pass a reference type variable, in fact, after the value of the variable (the object address) is passed, the modification to the variable will affect the value of the object pointed to by the other variable.

 

4. Finally, let's talk about when to use the structure and what classes to use.

We know that the structure is stored in the stack, and the stack has a small space, but the access speed is fast, the heap space is large, but the access speed is relatively slow. so when we describe a lightweight object, we can define it as a structure to improve efficiency. such as vertices, rectangles, and colors. These objects are lightweight objects, because they only need a small number of fields to describe them. When describing a heavyweight Object, we know that the object of the class is stored in the heap space, and we define the heavyweight Object as a class. they all indicate that they can contain data structures of data members and function members. Different from the class, the structure is a value type and does not require heap allocation. A variable of the structure type directly contains the data of the structure, and a variable of the class type contains references to the data (this variable is called an object ). The struct type is applicable to lightweight objects such as dots, rectangles, and colors. Although a vertex may be represented as a class, the structure is more effective in some schemes. In some cases, the structure cost is low. For example, if an array containing 1000 vertex objects is declared, additional memory will be allocated to each referenced object. SoThe structure is suitable for representing 1 lightweight object.

I will also use the structure for another reason. when we pass values in variables, I just want to pass the object copy instead of the Object Reference address, so we can also use the structure at this time.

 

The above is my personal summary. It is inevitable that there will be flaws in some areas. Thank you for your correction .!

Differences between struct and classes in C #

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.