Re: Two questions about C# datatypes

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Piotrekk wrote:
Hi

1. int is value type so it is stored on stack. class is reference type
and it is stored on heap.
What is where when we declare class which contains sturct which
contains int. I suppose that even in this example ALL value types are
on stack. Otherwise I wouldn't understand it at all since visual
studio C# project puts evertyhing into a class. Since classes are ref
types I assume that everything that is in the class and derives from
object goes to heap. Is that true?

2. How exactly compiler detects type if an object such that it can
detect wrong casts? I would appreciate also any links.

Kind regards
Piotr Kolodziej

Value types in classes is stored inside the class. Reference types in classes stores a reference in the class to the object on the heap.

For your example, a class containing a struct will create an object where the struct is part of the memory allocated to the object. The int inside the struct is thus inside the struct.

In other words, like this:

reference -> [ Object ---- [ Struct --- [ Int32 ] --- ] ---- ]

An object has a hidden pointer to a structure containing information about the class it has been created from. That's how GetType() can get the right Type object, how "is" and "as" works, etc.

--
Lasse Vågsæther Karlsen
mailto:lasse@xxxxxxxxxxx
http://presentationmode.blogspot.com/
PGP KeyID: 0xBCDEA2E3
.



Relevant Pages

  • Re: Question about Value Types
    ... struct MyValueType ... int Field1; ... populate the fields of a struct. ... alternative is to create two versions of this object - a reference type ...
    (microsoft.public.dotnet.framework)
  • RE: General Question About Structs and Stack
    ... The memory slot for a variable is stored on either the stack or the heap. ... That includes reference type variables - the variable itself is on the stack, ... method will always be on the stack, whereas a struct variable which is an ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Declaring array of references.
    ... generator, where speed is the only criterion. ... values will also be on the heap. ... I also assume that references are the size of one int, ... heap and the contents of the struct copied into it. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: General Question About Structs and Stack
    ... > A struct is stored on the stack and a class on the heap. ... > A struct is a value type while a class is a reference type. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: struct on the stack... sometimes on the heap?
    ... as a field in a class, no - it goes on the heap as ... A struct never "contains" (in terms of memory ... layout) a reference type; it contains a reference ...
    (microsoft.public.dotnet.languages.csharp)