开发者

copy struct which contains another struct

开发者 https://www.devze.com 2023-01-08 20:10 出处:网络
struct is a value type in C#. when we assign a struct to another struct variable, it will copy the values. how 开发者_Go百科about if that struct contains another struct? It will automatically copy the

struct is a value type in C#. when we assign a struct to another struct variable, it will copy the values. how 开发者_Go百科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.

0

精彩评论

暂无评论...
验证码 换一张
取 消