In .NET, Value Type and Reference Types are forms an element of confusion between both developers and the students. Many of us take this as granted that Value Types are allocated in Thread Stack ( a 1 MB local stack created per Thread) and on each method calls the local value types are allocated in the Stack such that after the call ends, the object is deallocated. On the contrary, the reference types we know are those which are always allocated in heap (which is not always true, I will discuss later) and even though they are used as locals, and will be deallocated only after an interval by a separate Thread that is running with any .NET process (called finalizer thread) which occationally starts finding the memory blocks on Heap storage and compact and store only the reachable objects called Garbage Collector. Well, in this post, I am not going to cover the details of Garbage Collection, but rather I will focus more on Value Types and Reference Types that I know personally to clear any doubt regarding them in terms of IL constructs. So after reading the post, you will know some of the basics of IL too. To tell you the truth, I have been trying to start blogging on this topic long ago, but could not get chance to finish it, but as my buddy @ZenWalker asked me a couple of questions, which I had to answer, I considered myself writing a blog on the same such that it benefits both him and all other people. His questions sounds like this : If System.ValueType inherits System.object, then all valuetypes are object. right?
If so,
1) Why do we say c# isnt pure Object Oriented because Value Types are not objects.
2) Value Types gets created over stack because to save space over heap or may be for performance right because heap creation takes time.
3. Why are Value Types struct and not class if they both are objects. To avoid complexity for simple types??
4. Why we have to do boxing and unboxing if valuetypes are objects too, or just to copy from stack to heap n back on??
Well the questions sounds quite interesting to me to answer and lets answer then knowing whats going on under the hood of a normal C# application and lets demonstrate them with code.Read more: Dot net tricks
QR:
If so,
1) Why do we say c# isnt pure Object Oriented because Value Types are not objects.
2) Value Types gets created over stack because to save space over heap or may be for performance right because heap creation takes time.
3. Why are Value Types struct and not class if they both are objects. To avoid complexity for simple types??
4. Why we have to do boxing and unboxing if valuetypes are objects too, or just to copy from stack to heap n back on??
Well the questions sounds quite interesting to me to answer and lets answer then knowing whats going on under the hood of a normal C# application and lets demonstrate them with code.Read more: Dot net tricks
QR:
0 comments:
Post a Comment