C# - How to create a structure?

Learn about the structure in C# with the help of example.
Submitted by Nidhi, on November 08, 2020 [Last updated : March 22, 2023]

Structure in C#

A structure is a value type that contains different types of data members inside it. Here, we will use the struct keyword to create a structure in our program.

Here, we will create a structure that contains the record of students and then print student information on the console screen.

C# program to create a structure

The source code to create a structure is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to demonstrate the 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 S1 = new Student();
        Student S2 = new Student();
        
        S1.SetStudent(101, "Rohit", 5000);
        S2.SetStudent(102, "Virat", 8000);

        S1.PrintStudent();
        S2.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 two instances S1 and S2 of structure Student. Then we set the student information and then printed the student information for both instances of Student structure.

C# Basic Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.