How to Use Structs in C#



A structure in C# is an aggregation of related data of different data type. A structure is initialized using a ‘struct’ keyword. A struct in C# cannot be inherited. It is implicitly sealed. Though structure is different from a class, they both have similar syntax.
A Structure in C# differs from class in a few ways and they are:
• Structures are value types while a class is of reference type
• Structures do not support inheritance where as inheritance is an important property of a class.
• Classes are initialized automatically with default constructors while structs do not contain default constructors.
Step 1: Implementation
The following code snippet uses struct in C# to store details of student. The structure student contains three member variables; name, age and gender of data types string, integer and character respectively. Notice that the member variables are declared as in class. The only difference is that the ‘class’ keyword is replaced by the ‘struct’ keyword.
Code - Structure

An object ‘Stud’ is created for the struct Student. The member variables are accessed using the dot operator, similar to class.
Step 2: Output
When the name, age and gender of the struct are accessed in the writeline statement, the stored values of the same get printed. The structure is instantiated and used similar to a class. The output is as follows:
Output