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.
- Do I correctly understand that when I create an instance of
SomeClass
itsSomeStruct
instance will be placed in Heap (meanwhile pointer for this struct instance lies in Stack)? - When I call
someClass.DoStaff()
new instance ofSomeStruct
is created within corresponding stack frame ofDoStuff
method, right? Then pointer now points to new struct instance in Stack? - 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