![]() |
VOOZH | about |
Structure is a value type and a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types. C# provide the ability to use pre-defined data types. However, sometimes the user might be in need to define its own data types which are also known as User-Defined Data Types. Although it comes under the value type, the user can modify it according to requirements and that's why it is also termed as the user-defined data type.
Defining Structure: In C#, structure is defined using struct keyword. Using struct keyword one can define the structure consisting of different data types in it. A structure can also contain constructors, constants, fields, methods, properties, indexers and events etc.
Access_Modifier struct structure_name
{
// Fields
// Parameterized constructor
// Constants
// Properties
// Indexers
// Events
// Methods etc.
}Data Stored in P1 is Keshav Gupta, age is 21 and weight is 80
Copy Structure: In C#, user can copy one structure object into another one using '=' (Assignment) operator.
Structure_object_destination = structure_object_source;
Values Stored in P1 Name: Keshav Gupta Age: 21 Weight: 80 Values Stored in P2 Name: Keshav Gupta Age: 21 Weight: 80
Nesting of Structures: C# allows the declaration of one structure into another structure and this concept is termed as the nesting of the structure.
Values Stored in p1 Name: Raman Age: 12 City: ABC_City State: XYZ_State
Important Points about Structures:
Difference Between Structures and Class :
| Category | Structure | Class |
|---|---|---|
| Data Type | Value Type | Reference type |
| Assignment Operation | Copies the value | Copies the reference |
| Parameterless Constructors | Not Allowed | Allowed |
| Inheritance | Not supported | Always supported |