简体   繁体   中英

struct instance as member of class C#

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM