4

I'm not even sure if I'm using the right terms here, but if I have a code like this: (in C#)

Object object1;
Object object2;
object1 = new Object();

object2 = object1;

Will object2 take up as much space as object1, or just point to the instance created at object1?

If I'm not using the correct terms to express myself properly, by all means tell me as well.

  • The object named by `object2` *is the same object* as named by `object1` after the final assignment. An assignment of a [Reference Type](http://msdn.microsoft.com/en-us/library/490f96s2.aspx) does *not* create a copy/clone/duplicate. – user2864740 Mar 18 '14 at 18:27

4 Answers4

8

A reference takes exactly one word of memory. That's 32 bits in a 32 bit application, 64 bits in a 64 bit application, etc.

Both variables take up exactly one word of memory, since they are of reference types. There is also some amount of memory, somewhere, that holds however much is needed for one actual object instance. Both of those variables in your program happen to contain a reference to that object, but they'd take up the same amount of space even if they didn't. (A null reference takes up the same space as a valid reference, after all.)

Servy
  • 202,030
  • 26
  • 332
  • 449
  • 1
    Why does it take up more bits in a 64 bit application? Sorry for sounding incompetent, but I'm just curious – user1974555 Mar 18 '14 at 18:29
  • 1
    @user1974555 The *definition* of a 64 bit application is that all references are 64 bits. It is a 64 bit application because the size of all references are 64 bits, the size of a reference isn't 64 bits because it's a 64 bit application. – Servy Mar 18 '14 at 18:29
  • 1
    What's the use of taking up more space? To be able to have more references or what? – user1974555 Mar 18 '14 at 18:31
  • @user1974555: To be able to address more memory. – SLaks Mar 18 '14 at 18:31
  • 1
    +1 for specifying "somewhere in memory", and not using heap/stack – Habib Mar 18 '14 at 18:35
1

You can get the size by querying in code IntPtr.Size returning the correct size based on the 32 or 64 bit process you are running in. So each reference will take up IntPtr.Size bytes

http://msdn.microsoft.com/en-us/library/system.intptr.size(v=vs.110).aspx

C# sizeof object pointer (SAFE context)

Community
  • 1
  • 1
Chad Dienhart
  • 5,024
  • 3
  • 23
  • 30
0

object2 points at the same underling object on the heap as object1. Now if this was a value type and in a method scope, then it would be added to the stack and take up more memory.

If you understand the concept of a C or C++ pointer, they are related.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • If the object was a value type it'd be boxed, making it a bit more complex than that... – Servy Mar 18 '14 at 18:27
0

It will point to the same instance, you will just have two variables referencing the same object on the heap.

w.b
  • 11,026
  • 5
  • 30
  • 49