Differences between class and struct in NET

Source: Internet
Author: User
In the era of process-oriented programming without a class, struct is a powerful tool for encapsulating data. However, since object-oriented programming, the class has been born, and everyone is shouting "Everything is an object", holding the class in their mouths, basically using the class can replace struct in any situation. However, you should not forget that "existence has its value", so struct still has its role and advantages. To know how to use it right, you must first thoroughly understand the differences between the two.

 

   Many times, when I mention class and struct, many new beginners may not see the differences between them. Indeed, the syntax is almost the same, but its essence is completely different: class is a reference type, struct is a value type, that is, the storage method in the memory is different, resulting in a series of differences. Therefore, only by having a deep understanding of the content related to memory allocation can we be able to better control it.

   Class is a basic concept of object-oriented programming. It is a type of custom data structure, usually including fields, attributes, methods, constructors, indexers, and events. In. NET, all classes are inherited from System. object class is a reference type. That is to say, when we create a new class instance, the Object stores the reference address of the actual data of the instance, the object value is stored in the managed heap.

 

   Struct (structure) is a value type used to organize a set of related information variables into a single variable entity. All structures are inherited from the System. ValueType class, which is a value type. We can use struct like int or char. The struct instance is allocated to the thread stack. It stores the value instead of the pointer to the value.

 

After understanding the nature of class and struct, We can summarize the differences between them through analysis and experiment:

(1) essence: class is a reference type, and struct is a value type.
(2) function: class is the encapsulation of behaviors and used to express objects, while struct is the encapsulation of data and used to store data.
(3) Inheritance: class supports inheritance from class and interface, while struct only supports inheritance interface. Struct cannot inherit from the class or be the base class of the class.
(4) constructor: class can declare non-argument constructor and destructor. struct can only declare constructor with parameters, and cannot declare destructor.
(5) about instantiation: The new Keyword should be used for the class, while the new Keyword can be used for struct. struct initializes the declaration process, all member variables are 0 or null by default.
(6) Abstraction: A class can be a real abstract class (abstract) and can declare abstract Functions. struct cannot.
(7) about overloading: class can declare protected members, virtual members, sealed members, and override members. struct cannot, but it is worth noting that struct can reload System. the three Virtual Methods of the Object, Equals (), ToString (), and GetHashTable ().
(8) Comparison: There are two types of comparison: Equals and =, that is, the value is equal and the reference is the same, and the two struct can be determined directly by =.
(9) Destruction: the class instance is recycled by the garbage collector to ensure that the memory is recycled. The struct variable is automatically released after use.
(10) parameter transfer: class variables are passed by address, while struct variables are passed by value.

 

   Since the class can almost completely replace struct to implement all the functions, is there any need for struct? In at least the following situations, we should consider using struct instead of class:

   You can consider struct when implementing a structure for storing data.
   You can consider struct when considering compatibility issues with some unmanaged code communications.

All of these are the reasons why struct has a place. Of course there may be more to say, but I don't know.

Reference a classic example

(1) define interfaces

 interface IPerson{
void GetSex();
}

(2) define a class

   Public class Person
   {
       Public Person ()
       {
       }

       Public Person (string name, int age)
       {
           _ Name = name;
           _ Age = age;
       }

       Private string _ name;

       Public string Name
       {
         Get {return _ name ;}
         Set {_ name = value ;}
       }

       Private int _ age;

       Public int Age
       {
         Get {return _ age ;}
         Set {_ age = value ;}
       }
   }

(3) define the structure

   // It can inherit from interfaces and cannot inherit classes or structures
   Struct Family: IPerson
   {
       Public string name;
       Public int age;
       Public bool sex;
       Public string country;
       Public Person person;

       // Cannot contain explicit no-argument constructor and destructor
       Public Family (string name, int age,

                 Bool sex, string country, Person person)
       {
           This. name = name;
           This. age = age;
           This. sex = sex;
           This. country = country;
           This. person = person;
       }

       // You cannot implement protected, virtual, sealed, and override members.
       Public void GetSex ()
       {
           If (sex)
               Console. WriteLine (person. Name + "is a boy .");
           Else
               Console. WriteLine (person. Name + "is a girl .");
       }

       Public void ShowPerson ()
       {
           Console. WriteLine ("This is {0} from {1 }",

                           New Person (name, 22). Name, country );
       }

       // The ToString virtual method can be reloaded.
       Public override string ToString ()
       {
           Return String. Format ("{0} is {1}, {2} from {3 }",

               Person. Name, age, sex? "Boy": "Girl", country );
       }
   }

   This article discusses class and struct so far, in. NET, the discussion of class and struct will involve understanding of the reference type and value type, and further extend the tentacles to the advanced topic of variable memory allocation, therefore, it is necessary for us to understand its operating mechanism, grasp the differences and application scenarios, so that we can grasp the content at this level in the ordinary system design.

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.