Copy struct that contains another structure

struct is the type of value in C #. when we assign struct another struct variable, it copies the values. how about a struct containing another struct ? Will it automatically copy the values โ€‹โ€‹of the internal struct ?

+4
source share
2 answers

Yes it will. Here is an example showing this 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.BY = 2; // Show that both values are copied. Foo foo2 = foo; Console.WriteLine(foo2.X); // Prints 1 Console.WriteLine(foo2.BY); // Prints 2 // Show that modifying the copy doesn't change the original. foo2.BY = 3; Console.WriteLine(foo.BY); // Prints 2 Console.WriteLine(foo2.BY); // Prints 3 } } 

How about whether this structure contains a different structure?

Yes. In general, although it might be a bad idea to create such complex structures, they usually should contain only a few simple values. If you have structures inside structures inside structures, you might wonder if the reference type is suitable.

+9
source

Yes. It is right.

+1
source

Source: https://habr.com/ru/post/1316461/


All Articles