In depth analysis of the structure defined by struct in C programming

  • 2021-09-05 00:41:46
  • OfStack

Structures are defined using the struct keyword, such as:


public struct PostalAddress
{
 // Fields, properties, methods and events go here...
}

Structures share most of the same syntax as classes, but structures are more limited than classes:

In a structure declaration, a field cannot be initialized unless it is declared as const or static. Structures cannot declare default constructors (constructors without arguments) or destructors. Structure is copied at assignment time. When a structure is assigned to a new variable, all data is copied, and any modifications made to the new copy do not change the data of the original copy. When using collections of value types, such as Dictionary < string, myStruct > ), be sure to keep this one in mind. Structures are value types, while classes are reference types. Unlike classes, structures can be instantiated without the new operator. Structure can declare constructors with parameters. A structure cannot inherit from another structure or class, and cannot be used as the base of a class. All structures are directly inherited from System. ValueType, which is inherited from System. Object. Structure can implement interfaces. Structures can be used as types that can be null, so they can be assigned an null value.

The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is equally convenient to represent a point as a class using an automatically implemented property, it is more efficient to use a structure in some cases. For example, if you declare an array of 1000 Point objects, you need to allocate more memory in order to reference each object; In this case, using structure can save resources. Because. NET Framework contains an object named Point, the structure in this example is named "CoOrds".


public struct CoOrds
{
 public int x, y;

 public CoOrds(int p1, int p2)
 {
 x = p1;
 y = p2;
 }
}

It is an error to define a default (no argument) constructor for a structure. It is also an error to initialize the instance field in the structure. Structure members can only be initialized in two ways: 1 by using a parameterized constructor, and 2 by accessing the members separately after the structure is declared. Any private or otherwise made inaccessible member can only be initialized in the constructor.
If you create a structured object using the new operator, the structured object is created and the appropriate constructor is called. Unlike classes, structures can be instantiated without the new operator. In this case, there is no constructor call, so the allocation efficiency can be improved. However, until all fields are initialized, the fields remain unassigned and the objects are unavailable.
When a structure contains a reference type as a member, the default constructor for that member must be explicitly called, otherwise the member will remain unassigned and the structure will not be available. (This will result in compiler error CS0171.)
For structures, there is no inheritance like classes. A structure cannot inherit from another structure or class, and cannot be used as the base of a class. However, the structure inherits from the base class Object. The structure can realize the interface in the same way.
You cannot declare a class using the struct keyword. In C #, classes and structures are semantically different. Structures are value types, while classes are reference types.

Unless you need to reference type semantics, declaring smaller classes as structures can improve the processing efficiency of the system.
Example 1
Describe
The following example demonstrates struct initialization using default and parameterized constructors.
Code


 public struct CoOrds
{
 public int x, y;

 public CoOrds(int p1, int p2)
 {
 x = p1;
 y = p2;
 }
}


 // Declare and initialize struct objects.
class TestCoOrds
{
 static void Main()
 {
 // Initialize: 
 CoOrds coords1 = new CoOrds();
 CoOrds coords2 = new CoOrds(10, 10);

 // Display results:
 Console.Write("CoOrds 1: ");
 Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);

 Console.Write("CoOrds 2: ");
 Console.WriteLine("x = {0}, y = {1}", coords2.x, coords2.y);

 // Keep the console window open in debug mode.
 Console.WriteLine("Press any key to exit.");
 Console.ReadKey();
 }
}


Output:


 CoOrds 1: x = 0, y = 0
 CoOrds 2: x = 10, y = 10

Example 2
Describe
The following example illustrates one function unique to the structure. It creates an CoOrds object without using the new operator. If you replace struct with class, the program will not compile.
Code


 public struct CoOrds
{
 public int x, y;

 public CoOrds(int p1, int p2)
 {
 x = p1;
 y = p2;
 }
}


 // Declare a struct object without "new."
class TestCoOrdsNoNew
{
 static void Main()
 {
 // Declare an object:
 CoOrds coords1;

 // Initialize:
 coords1.x = 10;
 coords1.y = 20;

 // Display results:
 Console.Write("CoOrds 1: ");
 Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);

 // Keep the console window open in debug mode.
 Console.WriteLine("Press any key to exit.");
 Console.ReadKey();
 }
}


Output:


 CoOrds 1: x = 10, y = 20


Related articles: