What is copy structure?
In C#, a "copy structure" usually refers to creating a copy of a structure object. When you have a structure (also known as a value type), you can duplicate its values and create a new, independent copy of the data.
Unlike reference types (e.g., classes), where assigning one variable to another merely creates a reference to the same object, copying a structure creates a distinct copy of the data, and changes made to one copy will not affect the other.
Here's an example of copying a structure in C#:
struct StudentRecord
{
public string Id;
public string FirstName;
public string LastName;
public int ClassGrade;
}
class Program
{
static void Main()
{
StudentRecord std1 = new StudentRecord();
std1.Id = "1";
std1.FirstName = "john";
std1.LastName = "smith";
std1.ClassGrade = 10;
StudentRecord std2 = std1; //copies std1 into std2
// Modifying std2 will not affect std1, as they are independent copies
std2.Id = "2";
std2.FirstName = "stuart";
std2.LastName = "broad";
std2.ClassGrade = 9;
Console.WriteLine("Display all field values std1");
Console.WriteLine($"Id: {std1.Id}");
Console.WriteLine($"Firt Name: {std1.FirstName}");
Console.WriteLine($"Last Name: {std1.LastName}");
Console.WriteLine($"Class Grade: {std1.ClassGrade}");
Console.WriteLine("Display all field values std2");
Console.WriteLine($"Id: {std2.Id}");
Console.WriteLine($"Firt Name: {std2.FirstName}");
Console.WriteLine($"Last Name: {std2.LastName}");
Console.WriteLine($"Class Grade: {std2.ClassGrade}");
}
}
In this example, we have a 'StudentRecord' structure with 4 fields ('Id', 'FirstName', 'LastName, 'ClassGrade'). We create an instance std1 and then create a copy std2 by assigning std1 to it. After modifying 'std2.Id', 'std2.FirstName', 'std2.LastName', 'std2.ClassGrade' we observe that all properties of 'std1' remains unchanged, showing that they are independent copies of the data.
Output of the above program is:
Display all field values std1
Id: 1
Firt Name: john
Last Name: smith
Class Grade: 10
Display all field values std2
Id: 2
Firt Name: stuart
Last Name: broad
Class Grade: 9
Copying structures is often useful when you want to pass data between methods or store snapshots of data in different variables without altering the original data.