Home > Mobile >  struct instance as member of class C#
struct instance as member of class C#

Time:08-07

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.

CodePudding user response:

#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

  • Related