This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Where are .NET local variables stored?
function storeonstack()
{
int a;
int b;
int c;
a=1;
b=1;
a=2
c=2;
}
Can Some body explain me how these value types are stored on stack?
Practically speaking*, value types are stored on the stack if they are local variables within a method, or on the heap if they are members of a reference type. Sometimes, local variables may also be stored on the heap if they are included in a closure. This is required so that the variables can continue to live after the function exits (and the stack frame is cleaned up). Local variables may also be stored in registers when they are used in operations, before being spilled back to the stack. Depending on JIT optimizations, local variables may only exist in registers, or may not exist at all. Member variables should always exist, though.
*Yes, technically, there's no guarantee that things like stack and heap exist, but let's be honest, on most, if not all, .NET implementations, there is a stack and a heap as in C programs.
It is an implementation detail and depends upon compiler. It may vary from compiler to compiler.
The Truth About Value Types
The stack is an implementation detail
Related
This question already has answers here:
Why don't structs support inheritance?
(10 answers)
Closed 9 years ago.
I am reading CLR via C# by Jeffery Richter and it says a struct is a value type and cannot be inherited.
Are there any technical or philosophical reasons?
ADD 1 - 5:53 PM 11/11/2020
Every decision, no matter how reasonable or accidental it may look, has its impact, subtle or profound. We try to decouple things, sometimes by creating new coupling...
Edit: There are serious editorial concerns about this post, apparently. See comment section.
A little of both.
Philosophically, it works out - there are classes, which are the "real" building block for object oriented programming, and there are structs, which are lightweight data types for storage but allow object-like method calls for familiarity and convenience.
Technically, being a "value type" means that the entire struct - all of its contents - are (usually) stored wherever you have a variable or member of that type. As a local variable or function parameter, that means on the stack. For member variables, that means stored entirely as part of the object.
As a (primary) example of why inheritance is a problem, consider how storage is affected at a low level if you allowed structs to have subtypes with more members. Anything storing that struct type would take up a variable amount of memory based on which subtype it ended up containing, which would be an allocation nightmare. An object of a given class would no longer have a constant, known size at compile time and the same would be true for stack frames of any method call. This does not happen for objects, which have storage allocated on the heap and instead have constant-sized references to that storage on the stack or inside other objects.
This is just an intuitive, high-level explanation - See comments and other answers for both expanded and more precise information.
Edit: The link in the comments to Eric Lippert's article The Stack Is An Implementation Detail, is now located on his personal blog site.
Because it is the way structs are represented in .NET. They are value types and value types don't have a method table pointer allowing inheritance.
You may find the answers to SO Question Why are .NET value types sealed? relevant. In it, #logicnp refers to ECMA 335, which states:
8.9.10 Value type inheritance
[...]
Will be sealed to avoid dealing with the complications of value slicing.
The more restrictive rules specified here allow for more efficient implementation without severely compromising functionality.
This question already has answers here:
Why are structs stored on the stack while classes get stored on the heap(.NET)?
(10 answers)
Closed 5 years ago.
I heard that variables are stored in stack and objects are stored in heap.
If i declare variable as var password= "abc".Now where this password is going to store(heap /stack)
Where an object is stored is not something you should be worrying about in the general case, but, as everytime this question crops up in SO, commentaries and answers crop up spreading the mythical and false belief that value types are stored in the stack and reference types are stored in the heap. No, no and no!
Thnink of it this way, its better: reference types go on the heap, short lived value types go on the stack. Long lived value types (fields, captured variables in a closure) go on the heap. The storage mechanism has very much to do with the expected lifetime of a variable, its not all about the nature of the type of the variable.
If you really want to know the details, read this.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've been reading a book on C# and it explains that int, float, double etc. are "basic" types meaning that they store the information at the lowest level of the language, while a type such as 'object' puts information in the memory and then the program has to access this information there. I don't know exactly what this means as a beginner, though!
The book however does not explain what the difference is. Why would I use int or string or whatever instead of just object every time, as object is essentially any of these types?
How does it impact the performance of the program?
This is a very broad subject, and I'm afraid your question as currently stated is prone to being put on hold as such. This answer will barely scratch the surface. Try to educate yourself more, and then you'll be able to ask a more specific question.
Why would I use int or string or whatever instead of just object every time, as object is essentially any of these types?
Basically you use the appropriate types to store different types of information in order to execute useful operations on them.
Just as you don't "add" two objects, you can't get the substring of a number.
So:
int foo = 42;
int bar = 21;
int fooBar = foo + bar;
This won't work if you declared the variables as object. You can do an addition because the numeric types have mathematical operators defined on them, such as the + operator.
You can refer to an integer type as an object (or any type really, as in C# everything inherits from object):
object foo = 42;
However now you won't be able to add this foo to another number. It is said to be a boxed value type.
Where exactly these different types are stored is a different subject altoghether, about which a lot has been written already. See for example Why are Value Types created on the Stack and Reference Types created on the Heap?. Also relevant is the difference between value types and reference types, as pointed out in the comments.
C# is a strongly typed language, which means that the compiler checks that the types of the variables and methods that you use are always consistent. This is what prevents you from writing things like this:
void PrintOrder(Order order)
{
...
}
PrintOrder("Hello world");
because it would make no sense.
If you just use object everywhere, the compiler can't check anything. And anyway, it wouldn't let you access the members of the actual type, because it doesn't know that they exist. For instance, this works:
OrderPrinter printer = new OrderPrinter();
printer.PrintOrder(myOrder);
But this doesn't
object printer = new OrderPrinter();
printer.PrintOrder(myOrder);
because there is no PrintOrder method defined in the class Object.
This can seem constraining if you come from a loosely-typed language, but you'll come to appreciate it, because it lets you detect lots of potential errors at compile time, rather than at runtime.
What the book is referring to is basically the difference between value types (int, float, struct, etc) and reference types (string, object, etc).
Value types store the content in a memory allocated on the stack which is efficient where as reference types (almost anything that can have the null value) store the address where data is. Reference types are allocated on the heap which is less efficient than the stack because there is a cost to allocating and deallocating the memory used to store your data. (and it's only deallocated by the garbage collector)
So if you are using object every time it will be slower to allocate the memory and slower to reclaim it.
Documentation
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I've been programming C# for some months now but I've never encountered this till now; what does this instruction mean?
int a = 1, b;
It's same as:
int a = 1;
int b;
Above statement declare multiple variables of same datatype in single statement.
So A local variable declaration that declares multiple variables is equivalent to multiple declarations of single variables with the same type.
That means
int a=1, b;
indicates that a and b both has same data type i.e. int along with we initialize the variable a with value 1 and b has default int value i.e 0
So equivalently you can write it as
int a=1;
int b;
It depends on whether these are "locals" (method variables) or "fields" (instance variables).
For fields, it declares a and b as Int32; they are both initiaized to zero when the memory is wiped (newobj/initobj) prior to the constructor being called, and then a is assigned a value of 1 at the start of the constructor.
For locals, it declares a and b as Int32, and immediately assigns 1 to a. B has no defined value. The rules of "definite assignment" mean that it is not required to have a defined value. However, all values on the stack must have some value - and we could obtain that value by cheating (for example, writing a method in IL that implements "out", but simply dereferences the address). The actual value is Dependent on whether the init-locals flag is set. This is not a c# language feature, but the current compiler does include this flag. This means that the memory space for locals is erased (set to zero) at the start of the method. So the logical value will be zero, but for different reasons. There is no requirement for this to happen - so it is entirely an implementation detail.
It defines Integers "a" and "b" giving value 1 to a
a and b are integers
and a's value is one. b has no value yet
a was declared and initialized to zero while b was just declared.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What and where are the stack and heap
There is a difference in C# between the heap and stack. I've just realized that I always thought that the stack is RAM and the heap is a hard drive. But now I'm not sure if it's correct. If it isn't, then what's is the difference if they are stored in one place?
"The stack" (or more precisely the call stack) is automatically managed memory (even in "unmanaged languages" like C): Local variables are stored on the stack in stack frames that also contain the procedures or functions arguments and the return address and maybe some machine-specific state that needs to be restored upon return.
Heap memory is that part of RAM (or rather: virtual address space) used to satisfy dynamic memory allocations (malloc in C).
Yet, in C# heap and stack usage is an implementation detail. In practice though, objects of reference type are heap-allocated; value type data can both be stored on the stack and on the heap, depending on the context (e.g. if it's part of an reference-type object).