Program to Store Information of a Student Using Structure - (C# Basic Programs)
In C#, structures are user-defined value types that can hold a set of related data items. In this tutorial, we will discuss a C# program to store information of a student using a structure.
Syntax
The syntax for creating and using a structure in C# is as follows:
struct Student {
public int rollNo;
public string name;
public int age;
};
Example
using System;
namespace StudentInfo
{
struct Student
{
public int rollNo;
public string name;
public int age;
};
class Program
{
static void Main(string[] args)
{
Student s1;
Console.WriteLine("Enter Roll No:");
s1.rollNo = Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter Name:");
s1.name = Console.ReadLine();
Console.WriteLine("Enter Age:");
s1.age = Int32.Parse(Console.ReadLine());
Console.WriteLine("Details of Student:");
Console.WriteLine("Roll No: " + s1.rollNo);
Console.WriteLine("Name: " + s1.name);
Console.WriteLine("Age: " + s1.age);
}
}
}
Output
Enter Roll No:
1
Enter Name:
John
Enter Age:
21
Details of Student:
Roll No: 1
Name: John
Age: 21
Explanation
In the above program, we create a struct named Student that contains three fields: rollNo, name, and age. We then declare a variable of type Student, s1, and prompt the user to enter the necessary details.
Once the information has been entered, we display the information back to the user.
Use
The above program can be useful in many scenarios where there is a need to store data related to a student. This program can be further extended to store more information such as the student's address, phone number, grades, etc.
Summary
In this tutorial, we have discussed a C# program to store information of a student using a struct. We have seen the syntax, example, output, explanation, and use of using a struct in C#. By using structs, we can create custom data types that are easy to use and can help us organize data in a meaningful way.