CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2004
    Posts
    123

    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

  2. #2
    Join Date
    Apr 2006
    Posts
    220

    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.

  3. #3
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    Re: Why is value types on the stack???

    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  4. #4
    Join Date
    Jan 2007
    Posts
    491

    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
  •  





Click Here to Expand Forum to Full Width

Featured