Often times you need to store different types of data which is related to each other. For instance you may need to store name, age, salary and department of an Employee. You will require four variables to do this. These four variables tell you information about one employee. For 2 Employees, you will require 8 variables. This is extremely cumbersome. Such cases are handled using structures.
A structure in C# is a data type which can contain multiple variables of different data types. Let’s see how function can be used to store employee information.
using System;
namespace CSharpTutorials {
struct Employee {
public string emp_name;
public int emp_age;
public int emp_salary;
public string emp_department;
}
class Tutorial {
static void Main(string[] args) {
Employee employee1;
Employee employee2;
employee1.emp_name = "Mike";
employee1.emp_age = 30;
employee1.emp_salary = 100000;
employee1.emp_department = "sales";
employee2.emp_name = "Jasmine";
employee2.emp_age = 23;
employee2.emp_salary = 200000;
employee2.emp_department = "marketing";
Console.WriteLine("Name of Employee1:" + employee1.emp_name);
Console.WriteLine("Age of Employee1:" + employee1.emp_age);
Console.WriteLine("Salary of Employee1:" + employee1.emp_salary);
Console.WriteLine("Department Employee1:" + employee1.emp_department);
Console.WriteLine("\n\nName of Employee2:" + employee2.emp_name);
Console.WriteLine("Age of Employee2:" + employee2.emp_age);
Console.WriteLine("Salary of Employee2:" + employee2.emp_salary);
Console.WriteLine("Department Employee2:" + employee2.emp_department);
Console.ReadKey();
}
}
}
To access the variables withing the structure, write the name of the structure variable, followed by a dot and the name of the variable.
Apart from variables, a structure can also contain functions. This is explained in the following example.
In the above example, two functions have been added to the Employee structure. The storevalues method stores value in the member variables of the structure, while the displayinfo method displays values of all the member variables on the console screen.