What is nested structure?
In C#, a "nested structure" refers to a structure (also known as a value type) that is defined within another structure or a class. This means you can declare a structure inside another structure, just as you can declare a class inside another class.
The idea of nested structures allows you to organize related data within a hierarchical structure, making it more modular and readable. It also allows you to create complex data structures by combining multiple nested structures.
Here's an example of a nested structure in C#:
struct StudentRecord
{
public string Id;
public string FirstName;
public string LastName;
public int ClassGrade;
public Address Adrs;
}
struct Address
{
public string City;
public string State;
}
class Program
{
static void Main()
{
StudentRecord std1 = new StudentRecord()
{
Id = "1",
FirstName = "john",
LastName = "smith",
ClassGrade = 10,
Adrs = new Address()
{
City = "Lahore",
State = "Punjab"
}
};
Console.WriteLine($"City: {std1.Adrs.City}");
Console.WriteLine($"State: {std1.Adrs.State}");
}
}
In this example, we have two structures: 'Address' and 'StudentRecord'. The 'StudentRecord' structure contains one field of type Address, namely 'Adrs'. The 'Address' structure represents two fields 'City' and 'State'.
By using nested structures, we can define the addres of the studentRecord using the 'StudentRecord' structure. This allows us to organize related data in a clear and concise manner.
Nested structures can also be used within classes, providing similar benefits of organizing data hierarchically and creating more complex data structures.