C# struct

‮h‬ttps://www.theitroad.com

In C#, a struct is a value type that can contain data members and member functions. A struct is similar to a class, but has some important differences.

Here's an example of a simple struct:

public struct Person
{
    public string Name;
    public int Age;

    public void PrintInfo()
    {
        Console.WriteLine($"Name: {Name}, Age: {Age}");
    }
}

In this example, the Person struct has two public data members (Name and Age) and a public member function (PrintInfo) that can be called on a Person instance to print the person's information.

To create an instance of a struct, you use the new operator:

Person john = new Person();
john.Name = "John Smith";
john.Age = 30;
john.PrintInfo(); // outputs "Name: John Smith, Age: 30"

Because structs are value types, when you assign a struct to a variable or pass it as a parameter, a copy of the struct is created. This can lead to some unexpected behavior if you're not careful. For example, consider the following code:

Person john = new Person();
john.Name = "John Smith";
john.Age = 30;

Person jane = john;
jane.Name = "Jane Smith";
jane.Age = 25;

john.PrintInfo(); // outputs "Name: John Smith, Age: 30"
jane.PrintInfo(); // outputs "Name: Jane Smith, Age: 25"

In this example, jane is assigned the value of john, but then the values of jane's data members are changed. However, this does not affect the values of john's data members, because jane is a copy of john, not a reference to it.

Because of this behavior, it's generally recommended that you use structs for small, simple types that don't need to be passed by reference, and use classes for more complex types or types that need to be passed by reference.