In previous Mytour articles, you were introduced to methods and strings in C#. In the following article, Mytour continues to explore structures in C#.
Structures in C#
1. Structures in C#.
1.1. Definition of structures in C#.
1.2. Copying structures.
1.3. Nesting structures.
2. Some important considerations about structures in C#.
3. Comparing structures and classes in C#.
1. Structures in C#
Structures are a value type, a collection of variables of different data types in a single unit. It is similar to a class, as both are user-defined data types and contain a series of different data types. C# provides the ability to use predefined data types.
However, users can sometimes define their own data types, also known as user-defined data types. Although it is a value type, users can modify it as desired, which is why structures are referred to as user-defined data types.
1.1 Definition of Structure in C#
In C#, structures are defined using the struct keyword. By using the struct keyword, one can define a structure that includes various data types. A structure can also contain constructors, constants, fields, methods, properties, indexers, and events, among others.
- Syntax:
Below is the syntax for defining a structure in C#:
- Example: For a clearer understanding, readers can refer to the example of defining a structure in C# below:
Output:
- Explanation: In the provided code snippet, a structure named 'Person' is created with data members Name, Age, and Weight. In the main method, an instance P1 of the Person structure is created. Subsequently, P1 can access data members using the.(dot) operator.
1.2 Copying Structures
In C#, users can duplicate a structure object to another using the assignment operator '='.
- Syntax for copying structures: Structure_object_destination = structure_object_source;
- Example of copying structures in C#:
Output:
- Explanation: The data members of the Person structure are initialized with the assistance of P1, and the values of the data members can be replicated from P1 to P2 using the assignment operator '='.
1.3. Nesting Structures
C# permits declaring one structure inside another, and this concept is known as nesting structures.
- Example of nesting structures:
Output format:
2. Key Considerations About Structures in C#
- When a structure goes beyond scope, it will be automatically released.
- Quicker and easier to create than heap types.
- Using structures, copying variable values to the stack is more straightforward.
- Structures are value types, while classes are reference types.
3. Comparing Structures and Classes in C#
Here is a comparison table highlighting the differences between structures and classes in C#:
This article on Mytour introduces you to what a structure is in C#. Additionally, readers can explore more articles on Mytour to learn about arrays in C# or understand what strings are.