struct
is a value type in C#. when we assign a struct
to another struct variable, it will copy the values. how about if that struct
contains another struct
? It will automatically copy the values of the inner struct
?
Yes it will. Here's an example showing it in action:
struct Foo
{
public int X;
public Bar B;
}
struct Bar
{
public int Y;
}
public class Program
{
static void Main(string[] args)
{
Foo foo;
foo.X = 1;
foo.B.Y = 2;
// Show that both values are copied.
Foo foo2 = foo;
Console.WriteLine(foo2.X); // Prints 1
Console.WriteLine(foo2.B.Y); // Prints 2
// Show that modifying the copy doesn't change the original.
foo2.B.Y = 3;
Console.WriteLine(foo.B.Y); // Prints 2
Console.WriteLine(foo2.B.Y); // Prints 3
}
}
How about if that struct contains another struct?
Yes. In general though it can be a bad idea to make such complex structs - they should typically hold just a few simple values. If you have structs inside structs inside structs you might want to consider if a reference type would be more suitable.
Yes. That is correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With