Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy struct which contains another struct

Tags:

c#

.net

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?

like image 433
5YrsLaterDBA Avatar asked Dec 29 '22 09:12

5YrsLaterDBA


2 Answers

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.

like image 117
Mark Byers Avatar answered Dec 30 '22 23:12

Mark Byers


Yes. That is correct.

like image 26
Brian Genisio Avatar answered Dec 30 '22 21:12

Brian Genisio