VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/c-sharp-structures-set-1/

⇱ C# | Structures | Set - 1 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C# | Structures | Set - 1

Last Updated : 11 Jul, 2025

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. 
 

  • Syntax:
     
Access_Modifier struct structure_name
{

 // Fields 
 // Parameterized constructor 
 // Constants 
 // Properties 
 // Indexers 
 // Events 
 // Methods etc.
 
}
  • Example: 
     

  •  

Output: 
Data Stored in P1 is Keshav Gupta, age is 21 and weight is 80

 

  • Explanation: In the above code, a structure with name "Person" is created with data members Name, Age and Weight.In the main method, P1 of structure type Person is created. Now, P1 can access its data members with the help of .( dot ) Operator
     


Copy Structure: In C#, user can copy one structure object into another one using '=' (Assignment) operator.
 

  • Syntax:
     
Structure_object_destination = structure_object_source;
  • Example:
     

  •  

Output: 
Values Stored in P1
Name: Keshav Gupta
Age: 21
Weight: 80

Values Stored in P2
Name: Keshav Gupta
Age: 21
Weight: 80

 

  • Explanation: The data members of struct Person is initialized with the help of P1 and the values of data members can be copy to P2 by P1 using '='(assignment operator).


Nesting of Structures: C# allows the declaration of one structure into another structure and this concept is termed as the nesting of the structure.
 

  • Example:
     

  •  

Output: 
Values Stored in p1
Name: Raman
Age: 12
City: ABC_City
State: XYZ_State

 


Important Points about Structures: 
 

  • Once the structures go out of scope, it gets automatically deallocated.
  • Created much more easily and quickly than heap types.
  • Using structure it become easy to copy the variable's values onto stack.
  • A struct is a value type, whereas a class is a reference type.


Difference Between Structures and Class : 
 

CategoryStructureClass
Data TypeValue TypeReference type
Assignment OperationCopies the valueCopies the reference
Parameterless ConstructorsNot AllowedAllowed
InheritanceNot supportedAlways supported


 

Comment
Article Tags:
Article Tags:

Explore