-
July 31st, 2008, 07:11 AM
#1
Why is value types on the stack???
I have a very dead basic doubt about value types and reference types. The root object in .NET is System.Object and all others are derived from System.Object which is a reference type. Now all value types are derived again from System.Object. Value types are allocated in the stack wherein reference types are allocated on heap. Despite being derived from System.Object, how is value types a value type and allocated on the stack??
The question might sound very silly, but still the thought was nagging me constantly.
Thanks in advance for your answer.
Mmx
-
July 31st, 2008, 07:31 AM
#2
Re: Why is value types on the stack???
Keep it in mind this way. Primitive types are not stored in heap and are treated as value types no matter they are inherited from System.Object. It is built into their design by Microsoft people.
-
July 31st, 2008, 12:06 PM
#3
Re: Why is value types on the stack???
-
July 31st, 2008, 12:47 PM
#4
Re: Why is value types on the stack???
Keep in mind that when you compare two structs or primitive types, which are on the stack, you compare their CONTENT.
Code:
string str = "hello";
if(str = "hello") Console.WriteLine("Hello"); //will be executed
However, when you compare classes or two other objects which are on the heap, you acually compare their ADRESS IN MEMORY.
Code:
Point p1, p2; //assuming Point is a class
p1 = new Point(5, 6);
p2 = new Point(5, 6);
if(p1 == p2)
Console.WriteLine("Hello"); //will NOT be executed
Code:
Point p1, p2; //assuming Point is a class
p1 = new Point(5, 6);
p2 = p1; //now p2 refers to p1. once p1 will be changed - p2 will be changed too!
if(p1 == p2)
Console.WriteLine("Hello"); //will be executed
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|