Go The difference between a struct and a class in C #

Source: Internet
Author: User

Tag: value type string Val modifies the constructor member of the IMA object class assembly class

Often hear friends talking about the difference between a struct and a class in C #. Just this few days idle to have no matter, oneself summarizes, hope everybody pointing.

1. The first is the grammatical definition of the difference, this will not have to say. Define a class using the keyword class to define the struct using the keyword struct. There are many similarities between classes and structures in syntax.

To define the syntax of a class

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}

Defines the syntax for 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     }

From a grammatical point of view. Their syntax is much the same, and the members of a class can be defined almost within a struct, except for destructors. Why is this? Back answer.

2. Although we say that they are very similar in syntax, there are a few differences in grammar.

A. You can declare a field in a struct, but you cannot give an initial value when declaring a field. 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 1 fields in the class and assign the initial value to the field, it can be dropped, as in the following.

Class person{   private String name = "Jack";}

But if it does not work like this. Declare the 1 fields and assign a value to the field as follows.

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

So we say that only the members of the class can be defined directly under the class. For example, define member fields, attribute method constructors, and so on. The code above Name= "Jack", which we call "execution code", meaning that the code will work only when it is executed. And you just imagine, when is this code going to be executed? When creating an object of a class? Does that still need a constructor function? It is often seen that some beginners write such code directly below the class.

But someone else will say. Well, then why is it possible to assign a value when declaring a field of a class? The assignment expression is also 1 execution code AH? Why is this not an error? show you the code below and you'll know the truth.

When we use the C # compiler to compile this piece of code into an assembly, look at the code that Microsoft generated for us.

Expand the constructor and see what's in it!

Yes, C # compiler at compile time, if we declare the field when the field is assigned value, then the code assigned to the field of the C # compiler will be compiled when the assignment code into the constructor, in fact, strictly speaking, the class can not have the original value of the field. But Microsoft did something for us behind the scenes, We don't know.

Therefore, the execution code must be written in the method, regardless of the class and structure. Cannot be written directly below the structure or class. Because when the execution code is written in the method, the execution time of the execution code is determined, that is, when the method is called.

From the above, we can see. In essence, the fields of a class and struct cannot have an initial value. Only Microsoft syntactically allows us to assign values to the fields of a class when it is defined. But behind the scenes, Microsoft is actually putting the assigned execution code into the constructor. But the structure of Microsoft does not help us to do so. As for what is the reason for this. Looked up some information, also looked at the garden other Bo friend's article, the feeling can not persuade me, but I also can not think of 1 exactly reason why Microsoft wants to do this. Then let it go, hoping to understand the principles of the children's shoes.

B. About constructors.

First, about implicit constructors. We know that in 1 classes if we don't write any constructors for the class, the C # compiler will automatically generate 1 parameterless constructors for this class when compiling. We call this constructor an implicit constructor. But once we write an arbitrary 1 constructor for this class, the implicit constructor is not automatically generated.

This is not the case in structs, where implicit constructors exist in any case. Look at the code.

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

We use the New keyword to create a struct object, and we find that when we call the constructor, there are two constructors. There are 1 parameterless constructors.

Then we think, can you manually write 1 parameterless constructors? We have a very excited mood, try it.

The result is a gorgeous error. So we come to the conclusion that implicit parameterless constructors exist in the structure anyway, so programmers cannot manually add 1 parameterless constructors to the structure.

about constructors of course it's not just that. We know that in the constructor of a class we can write arbitrary code (provided that it conforms to C # syntax), although you can write arbitrary code in the constructor of the struct. But C # syntax is defined in the constructor of the struct, You must assign values to all the fields of the struct . Look at the code below.

Ah oh ..... An error has been made .....

We also know that properties can be defined in the structure, so there are children's shoes. Look at the code below.

This error, still suggests that we do not assign values to all the fields in the constructor, which is a problem for many children's shoes, eh, is not to assign values to all the fields in the constructor? I am now assigned a value. Why is the hint not assigned? Why can't we assign values to properties in the constructor and assign values to the fields? The reason is simple. Because the syntax requires that we assign values to all fields, although here we can see that the property is assigned a value to the field, we say that the property is the operation of the field, but it must be like this? We could completely write nothing in the set block of the attribute, if nothing is written, So is the property still in the Action field? So the attribute is not necessarily in the action field, we assign a value to the property in the struct's constructor, not to assign a value to the field, so we are going to assign a value to the field directly in the constructor.

C. How to create a struct object.

You can create a struct object without using the New keyword. Declare 1 variables directly. However, the fields in the struct object do not have an initial value, so you must assign a value to the field before using the field.

The reason is simple. Because the initial value cannot be given at the time of Declaration, although the constructor assigns a value to the field of the object, this way creates the struct object without calling the constructor, so the programmer must assign the value manually before using it. That's it for you.

The other 1 ways to create struct objects, like classes, are created using the New keyword, unlike creating a struct object by using the New keyword, the field of the struct object already has a value. The reason is not difficult to understand, the new keyword called the constructor, The struct constructor requires that all fields be assigned a value.

So, it's not hard to guess. Struct's parameterless constructor does something, assigns a value to all fields in a parameterless constructor, assigns a value of type 0 to a field of the reference type, and assigns a value of NULL to the fields of the referenced types.

D. structs cannot inherit from 1 other structures or classes, but interfaces can be implemented. Special is. Although structs cannot inherit from other classes or structs, all structs inherit from the ValueType class by default, The ValueType class is then inherited from the object class. So the struct object still owns the members of the Super class object. Look at the following Microsoft generated code to know.

3. The biggest difference between them is that a struct is a value-type class that is a reference type.

A struct is a value type, and when it is a 1 local variable, the variable is stored in the stack space, and the field of its object is stored directly in the variable. Just like this.

Unlike a class that references a type, a variable of a reference type stores the address of an object in the heap space, so when we pass a variable of 1 reference types, the value of the variable (the address of the object) is passed and the modification of the variable affects the value of the object to which the other 1 variables point.

4. Finally talk about when to use the structure, what to use the class.

We know that the structure is stored in the stack, and the stack has 1 characteristics, that is, the space is small, but the access speed is faster, the heap space is large, but the access speed is relatively slow. So when we describe 1 lightweight objects, we can define them as structures to improve efficiency. such as points, rectangles, colors, these objects are lightweight objects, Because they are described, only a small number of fields are required. When describing 1 heavyweight objects, 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 represent data structures that can contain data members and function members. Unlike classes, structs are value types and do not require heap allocations. A variable of a struct type directly contains the data of a struct, whereas a variable of a class type contains a reference to the data (the variable is called an object). struct types are suitable for lightweight objects that represent points, rectangles, and colors. Although a point may be represented as a class, the structure is more efficient in some scenarios. In some cases, the cost of the structure is lower. For example, if you declare an array that contains 1000 point objects, additional memory is allocated for each object that is referenced. So the structure fits to represent 1 lightweight objects.

I also use structures for 1 other reasons. When we pass the value of the variable, I just want to pass the object's copy, not the object's reference address, then this time can also use the structure.

Go The difference between a struct and a class in C #

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.