Introduction
A value type and an assortment of variables with various data types grouped together under one unit is called a structure. Given that they are both user-defined data types and may store a large number of different data types, they are nearly identical to classes. Pre-defined data types can be used with C#. User-Defined Data Types, as they are also called, are data types that the user may need to define on occasion. Even though it is a value type, the user can alter it to suit their needs, which is why it is also known as a user-defined data type.
Defining Structure
The struct keyword in C# is used to define structure. One can define a structure that contains various data kinds by using the struct keyword. Constructors, constants, fields, methods, properties, indexers, events, and other elements can also be found in a structure.
Syntax
AccessModifier struct structureName
{
// Fields
// Parameterized constructor
// Constants
// Properties
// Indexers
// Events
// Methods etc.
}
Example
public struct Employee
{
public int Id;
public string Name;
public int Rank;
}
var emp = new Employee
{
Name = "Jaimin Shethiya",
Rank = 183,
Id = 1
};
Console.WriteLine("{0} - {1}", nameof(emp.Id), emp.Id);
Console.WriteLine("{0} - {1}", nameof(emp.Name), emp.Name);
Console.WriteLine("{0} - {1}", nameof(emp.Rank), emp.Rank);

Constructor in Structure
A parameterless constructor is not allowed in a struct. It can only have a static constructor or parameterized constructors.
public struct Employee
{
public int Id;
public string Name;
public int Rank;
public Employee(int id, string name, int rank)
{
Id = id;
Name = name;
Rank = rank;
}
}
var emp = new Employee(1, "Jaimin Shethiya", 183);
Console.WriteLine("{0} - {1}", nameof(emp.Id), emp.Id);
Console.WriteLine("{0} - {1}", nameof(emp.Name), emp.Name);
Console.WriteLine("{0} - {1}", nameof(emp.Rank), emp.Rank);

Methods and Properties in Structure
Similar to classes, structs can have methods, auto-implemented properties, and other attributes.
public struct Employee
{
// Properties
public int Id { get; set; }
public string Name { get; set; }
public int Rank { get; set; }
// Method
public void SetEmployee()
{
Id = 1;
Name = "Jaimin Shethiya";
Rank = 183;
}
}
var emp = new Employee();
emp.SetEmployee();
Console.WriteLine("{0} - {1}", nameof(emp.Id), emp.Id);
Console.WriteLine("{0} - {1}", nameof(emp.Name), emp.Name);
Console.WriteLine("{0} - {1}", nameof(emp.Rank), emp.Rank);





Join the conversation! Your thoughts help the community grow.