C# Program to Demonstrate the Array of Structures
Last Updated :
29 Oct, 2021
An array of structures means each array index contains structure as a value. In this article, we will create the array of structure and access structure members using an array with a specific index.
Syntax
array[index].Structure(Details);
where index specifies the particular position to be inserted and details are the values in the structure
Example:
Input:
Insert three values in an array
Student[] student = { new Student(), new Student(), new Student() };
student[0].SetStudent(1, "ojaswi", 20);
student[1].SetStudent(2, "rohith", 21);
student[2].SetStudent(3, "rohith", 21);
Output:
(1, "ojaswi", 20)
(2, "rohith", 21)
(3, "rohith", 21)
Approach:
- Declare three variables id , name and age.
- Set the details in the SetStudent() method.
- Create array of structure for three students.
- Pass the structure to array index for three students separately.
- Display the students by calling DisplayStudent() method
Example:
C#
using System;
public struct Employee
{
public int Id;
public string Name;
public int Age;
public void SetEmployee( int id, string name, int age)
{
Id = id;
Name = name;
Age = age;
}
public void DisplayEmployee()
{
Console.WriteLine( "Employee:" );
Console.WriteLine( "\tId : " + Id);
Console.WriteLine( "\tName : " + Name);
Console.WriteLine( "\tAge : " + Age);
Console.WriteLine( "\n" );
}
}
class GFG{
static void Main( string [] args)
{
Employee[] emp = { new Employee(),
new Employee(),
new Employee() };
emp[0].SetEmployee(1, "Ojaswi" , 20);
emp[1].SetEmployee(2, "Rohit" , 21);
emp[2].SetEmployee(3, "Mohit" , 23);
emp[0].DisplayEmployee();
emp[1].DisplayEmployee();
emp[2].DisplayEmployee();
}
}
|
Output:
Employee:
Id : 1
Name : Ojaswi
Age : 20
Employee:
Id : 2
Name : Rohit
Age : 21
Employee:
Id : 3
Name : Mohit
Age : 23
Share your thoughts in the comments
Please Login to comment...