C# program to demonstrate the array of structures

Here, we are going to demonstrate the array of structures in C#.
Submitted by Nidhi, on November 08, 2020

Here, we will create the array of structure and then access structure members using array subscript with the specified index.

Program:

The source code to demonstrate the array of the structure is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to demonstrate the array of structure in C#

using System;

public struct Student
{
    public int Id;
    public string Name;
    public int Fees;

    public void SetStudent(int id, string name, int fees)
    {
        Id = id;
        Name = name;
        Fees = fees;
    }

    public void PrintStudent()
    {
        Console.WriteLine("Student details:");
        Console.WriteLine("\tID     : " + Id);
        Console.WriteLine("\tName   : " + Name);
        Console.WriteLine("\tFees   : " + Fees);
        Console.WriteLine("\n");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Student[] S = { new Student(), new Student() };
        
        S[0].SetStudent(101, "Rohit", 5000);
        S[1].SetStudent(102, "Virat", 8000);

        S[0].PrintStudent();
        S[1].PrintStudent();
    }
}

Output:

Student details:
        ID     : 101
        Name   : Rohit
        Fees   : 5000


Student details:
        ID     : 102
        Name   : Virat
        Fees   : 8000

Press any key to continue . . .

Explanation:

In the above program, we created a structure Student that contains data members Id, Name, and Fees. The Student structure contains two methods SetStudent() and PrintStudent().

The SetStudent() method is used to set the student information, and PrintStudent() method is used to print the student information on the console screen.

Now look to the Program class. The Program class contains the Main() method, The Main() method is the entry point for the program. Here, we created the array of structure Student, and then called the SetStudent() and PrintStudent() method for array elements.

C# Basic Programs »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.