Program to Store Data in Structures Dynamically - (C# Basic Programs)
In this tutorial, we will discuss a program in C# programming language that demonstrates how to store data in structures dynamically. The program will allow the user to enter data for multiple people and store it in a structure in memory.
Syntax
The basic syntax for creating a structure in C# is as follows:
struct Person {
public string Name;
public int Age;
}
To store data in a structure dynamically, we can use the List<T>
class in C#.
Example
using System;
using System.Collections.Generic;
struct Person {
public string Name;
public int Age;
}
class Program {
static void Main(string[] args) {
List<Person> people = new List<Person>();
while (true) {
Console.WriteLine("Enter a name (or 'done' to quit):");
string name = Console.ReadLine();
if (name == "done") {
break;
}
Console.WriteLine("Enter an age:");
int age = int.Parse(Console.ReadLine());
Person person = new Person();
person.Name = name;
person.Age = age;
people.Add(person);
}
Console.WriteLine("\nList of People:");
foreach (Person person in people) {
Console.WriteLine("Name: {0}\nAge: {1}\n", person.Name, person.Age);
}
}
}
Output
Enter a name (or 'done' to quit):
John
Enter an age:
25
Enter a name (or 'done' to quit):
Jane
Enter an age:
30
Enter a name (or 'done' to quit):
done
List of People:
Name: John
Age: 25
Name: Jane
Age: 30
Explanation
The program uses a List<T>
data structure to store the data entered by the user. The Person
structure contains two members, Name
and Age
. The program uses a while
loop to repeatedly prompt the user for input until the user enters "done". For each person entered by the user, a new Person
structure is created with the Name
and Age
members set to the input values, and this Person
structure is added to the list using the Add
method. Finally, the program uses a foreach
loop to print out the list of people entered by the user.
Use
This program demonstrates how to store data in structures dynamically using C# programming language. It can be used as a starting point for more complex programs that involve creating and managing dynamic data structures.
Summary
In this tutorial, we have discussed a program in C# programming language that demonstrates how to store data in structures dynamically. We have seen the syntax, example, explanation, use, and output of storing data in structures dynamically using C#. By writing programs like this, we can become more familiar with structures and data storage techniques in C#, which will be useful in future programming projects.