I feel completely lost in the logic of the following example code:

namespace StructInClass
{
    internal class Program
    {
        static void Main(string[] args)
        {
            SomeClass someClass = new SomeClass();
            someClass.DoStaff();
        }
    }


    public class SomeClass
    {
        private SomeStruct _someStruct;

        public SomeClass() =>        
            _someStruct = new SomeStruct();  
    
        public void DoStaff() => 
            _someStruct = new SomeStruct(4, 5); 
    }


    public readonly struct SomeStruct
    {
        public readonly int x;
        public readonly int y;

        public SomeStruct()
        {
            this.x = 0;
            this.y = 1;  
        }

        public SomeStruct(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }
}

I have several questions here.

  1. Do I correctly understand that when I create an instance of SomeClass its SomeStruct instance will be placed in Heap (meanwhile pointer for this struct instance lies in Stack)?
  2. When I call someClass.DoStaff() new instance of SomeStruct is created within corresponding stack frame of DoStuff method, right? Then pointer now points to new struct instance in Stack?
  3. Is there any sense to declare private field of SomeStruct type in terms of perfomance?

Googling gives me ambiguous answers.

推荐答案

#1. SomeClass is on the heap, the struct is inline in that heap memory (if SomeStruct was a class then it would be in a separate hea allocation)

#2 no - its on the heap

#3 - yes its inlined in the containing class as opposed to being a new heap allocation

Csharp相关问答推荐

Azure 表存储,帮我理清批处理操作的幕后情况

是否每次调用 Count 或 Length 属性时都会计算它们?

我正在try 单独为特定字符着色. (控制台、C#、.Net.)

去重流记录

正则表达式:当组不出现时返回 Null

无法用任意 colored颜色 绘制球体

如何在不使用“_id”键的情况下使用 c# 在 MongoDB 中避免重复插入?

通过 c# 脚本创建统一的 2d 动画

具有通用接口和参数的 C# DI

如何从编码的 base64 UTF 字符串中删除 BOM?

在不同项目的不同 c# 类中使用 appsettings 值

如何有效地使用可用内存比较 1,000 张图像

如何向 COM 公开“通用”C# 集合

无法将方法组转换为操作

Windows 窗体 C#,返回字符串数组始终为空

在没有 UI 线程的专用后端服务器上使用异步代码有优势吗?

任务延迟是否创建新线程?

如何使用 LookRotation 根据手部位置旋转对象?

Windows 11 下的 WPF C# MoveWindow 问题

C# 中的 StringBuilder 与 Span