1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

c# 構造体で個人的に誤解していたこと

Posted at

まずい例

構造体について、以下の例で全部の値がコピーされることは誰でも知っていると思います。

A a = new A();
A a2 = a; // aの中身の全てが、a2にコピーされる

次の例でも全部の値のコピーが発生します。コンストラクタ的な書き方なので発生しないような感覚でした。

A a = CreateA(); // CreateA()の結果の中身の全てが、aにコピーされる

確認コード

出力されるアドレス全てが異なることが確認できます。

using System;
struct MyStruct
{
    public int x;
}
class Program
{
    unsafe static void Main()
    {
        MyStruct a = new MyStruct { x = 5 };
        MyStruct b = a; // コピーされる

        Console.WriteLine($"アドレス: {(ulong)&a:X}");
        Console.WriteLine($"アドレス: {(ulong)&b:X}");

        MyStruct test = Create();
        Console.WriteLine($"アドレス: {(ulong)&test:X}");
    }
    public unsafe static MyStruct Create()
    {
        MyStruct ms = new();
        ms.x = 0;
        Console.WriteLine($"アドレス: {(ulong)&ms:X}");
        return ms;
    }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?