Reputation: 65
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.
SomeClass
its SomeStruct
instance will be placed in Heap (meanwhile pointer for this struct instance lies in Stack)?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?SomeStruct
type in terms of perfomance?Googling gives me ambiguous answers.
Upvotes: 3
Views: 168
Reputation: 50190
#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
Upvotes: 1