If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

then the compiler automaticly creat 5 copy of the variables(from the struct) in the stack? or it creat a copy of the variables only when i calls method that use a variable from the struct , for example

Re: struct in memory explanation

No, when you declare a struct, the same rules apply as when you declare a class - but they behave differently in a very specific way.
To actually create your struct in memory, you have to create one (in some code outside the struct, that uses it):

CarType car = new CarType();

The difference is that struct are value types, while classes are reference types. This means that, when you pass a struct to a function, or assign a it to another variable, the struct's instance is passed by value - it is copied. When you do the same with a class, both variables end up pointing to ghe same object. If you change a class-type object from within a function, the changes will remain when the function returns. This is called passing by reference (two things refer to the same object). If you do it to a struct, the changes will be lost, because you were changing a copy of the original.

Also, people often say that structs are allocated on the stack, while classes are allocated on the heap - this is true, but this is an implementation detail of the language, it is not an intrinsic property of the concepts of structs and classes themselves. The important distinction is the by-value vs by-reference semantics.

Write a few simple programs with some methods that take structs and classes as parameters and try it out yourself.