none
Is Value Type acting as Reference Type? RRS feed

  • Question


  • Hi All,

    I am a C++ programmmer and have just started learning the C# language.

    I read about the Common Type System provided by the .NET Framework which broadly categories the types into "Value" type and "Reference" type.

    Primitive datatypes and Structures fall under the "Value" type while Class falls under the "Reference" type.

    A Reference type has to be allocated memory using the "new" operator. This memory allocation happens on the managed heap. So what I understand here is that when we use a "new" operator, the type getting assigned will always be a Reference type.

    .i.e. an object of class Employee can be created as shown below:

    Employee

     

    emp = new Employee();


    A Value type gets memory as they are declared. The memory is allocated on the stack .i.e.

    Int32 nData = 107;

    but strangely you can declare a Value type as shown below:

    Int32 nData = new Int32();


    Below are my questions with respect to the above statement of using the the "new" operator with Value type:

    1. As I said earlier when we use a "new" operator, the type getting assigned will always be a Reference type. In that case a Value type when used with the "new" operator should actually raise a complier error?

    2. How is the memory allocation/deallocation managed for the above statement .i.e. is the memory allocated on managed heap and the reference is stored in the Value type? How does the deallocation happen?

    3. I think the above statement stands conflicting and should actually lead to a compiler error by .NET compilers since Value type should be assigned only values of that specify type while Reference type can actually hold references? Your views?

    Regards,
    Santosh. 

    Wednesday, December 16, 2009 6:35 AM

Answers

  • 1) The new keyword is used to invoke the constructor of that type, whether it is a referencetype or valuetype is irrelevant.

    2) Valuetypes are accessed directly on the stack. Referencetypes have a pointer, this pointer lives on the stack and points to the data of that referencetype on the heap. The deallocation happens through the Garbage Collector (.NET is managed, meaning we have the memory managed for us)

    3) I disagree, everything (well..not everything but thats not the point here) in .NET is an object, meaning everything in .NET is of a specific type. To construct the type we need to invoke the constructor of that type through the new keyword.

    A few nice links:

    a nice article about the heap & stack

    MSDN stuff about garbage collection in .NET
    • Proposed as answer by Geert van Horrik Wednesday, December 16, 2009 10:46 AM
    • Marked as answer by eryang Monday, December 21, 2009 2:29 AM
    Wednesday, December 16, 2009 8:13 AM