[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Is object a reference type?

Posted on 2006-05-10
7
Medium Priority
?
182 Views
Last Modified: 2011-10-03
Hi

I try this

object obj1 = 0;
object obj2 = obj1;

obj1 = 1;
MessageBox.Show(obj1.ToString());
MessageBox.Show(obj2.ToString());

It displays
1
0

I thought it should display
1
1

thanks
Paul
0
Comment
Question by:paulwhelan
7 Comments
 
LVL 21

Expert Comment

by:MogalManic
ID: 16647348
What you are seeing is called boxing.  The int is being automagically converted to an Integer object.  It also looks like the second object is being boxed as well, so obj1 points to a different object than obj2.
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 16647422
I was wrong.  I just compiled the above code and then ran the assembly through lutz's .net reflector and got this:
      object obj2 = 0;
      MessageBox.Show(1.ToString());
      MessageBox.Show(obj2.ToString());

so the answer is that the .net compiler has optomized the code.  But it also shows that even though obj1 not declared as an int, it still boxes like an int when assigned to another object.
0
 
LVL 1

Expert Comment

by:AtulRasal
ID: 16647505
Hi Paul,

Reference types actually hold the value of a memory address occupied by the object they reference. Consider the following piece of code, in which two variables are given a reference to the same object (for the sake of the example, this object is taken to contain the numeric property 'myValue').

object x = new object();
x.myValue = 10;
object y = x;
y.myValue = 20; // after this statement both x.myValue and y.myValue equal 20

This code illustrates how changing a property of an object using a particular reference to it is reflected in all other references to it.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 21

Expert Comment

by:MogalManic
ID: 16647506
OK, now I figured out what is happening:
  object obj1 = 0;   //boxes 0 as an object
  object obj2 = obj1;  //points obj2 to obj1

  obj1 = 1;  //boxes 1 as an object.  Now obj1 points to a different object that obj2

In otherwords, the .net is doing this pseudocode:

    obj1=1.ToIntegerObject();

when treated this way, you can treat int constants as immutable objects.  The following code:
     int num1 = 1;
      object obj1 = num1;
      object obj2 = obj1;
      num1 = 2;
      MessageBox.Show(obj1.ToString());
      MessageBox.Show(obj2.ToString());
will output 1 and 1 because each object is independant and you cannot change the value of the int constant without creating a new object.
This applies to ints as well.  If you run the following code:
  int num1=1;
  int num2=num1;
  num1+=5;
num 1 will be 6 num2 will be still 1.  The int's cannot be assigned to a reference to another int.  The only place where that is possible is
in function declarations.

  void foo(ref int intValue)
will pass the 'intValue' parameter by reference.  In other words, any change made to the intValue inside foo will be reflected back to the caller.
   
0
 

Author Comment

by:paulwhelan
ID: 16649226
So would it be the same to say

object obj1 = (object) 0;
object obj2 = obj1;

obj1 = (object) 1;
MessageBox.Show(obj1.ToString());
MessageBox.Show(obj2.ToString());
0
 
LVL 6

Accepted Solution

by:
neilprice earned 120 total points
ID: 16649989
Hi Paul,

First of all...

"object obj1 = (object) 0;"

This line of code is redundant since the very act of assigning an integer value (or any other) to an object boxes it anyway.  So that is equivalent to the line you typed before;

"object obj1 = 0;"

How to explain your original code:

The stack area of memory is used to handle value types (numerical data, enums and structs etc.).  The heap is used to handle reference type data (classes etc.).  

If you are working with value types then each time you make an assignment to them (and in your case 1 and 0 are value types since they are integer constants) then a new copy is created on the stack that can be manipulated independently of the others.

If you are working with reference types then each time you make an assignment to them then a new reference is created to an object on the heap.

This can be illustrated through the following short piece of code:

using System;
namespace Testing
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 5; // int is a value type
            object obj1 = x; // obj1 now points to an indepent copy of "5" on the stack
            object obj2 = obj1; // obj2 now points to an indepent copy of "5" on the stack
            x = 10; // changing the original stack value does not affect our other stack values
            Console.WriteLine(obj1.ToString()); // 5
            Console.WriteLine(obj2.ToString()); // 5
            MyRefTypeInt y = new MyRefTypeInt(); // A reference type simply to hold an int
                                                 // for this demonstration
            y.value = 5;
            obj1 = y; // obj1 is now referenced to y on the heap
            obj2 = obj1; // obj2 is now referenced to y on the heap
            y.value = 10; // changing y will changed obj1 and obj2 since they are references to the heap
            Console.WriteLine(obj1.ToString()); // 10
            Console.WriteLine(obj2.ToString()); // 10
            Console.ReadLine();
        }
    }

    // Just making a simple reference type for purposes of this demonstration
    class MyRefTypeInt
    {
        public int value;

        public override string ToString()
        {
            return value.ToString();
        }
    }
}

Hope this helps,
Neil
0
 
LVL 6

Expert Comment

by:neilprice
ID: 16650013
Ooops...

the comments on these lines;

object obj1 = x; // obj1 now points to an indepent copy of "5" on the stack
object obj2 = obj1; // obj2 now points to an indepent copy of "5" on the stack

Should also let you know that the new indepent copy is actually being stored on the heap as a boxed object would be ;)

Sorry!
Neil
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Screencast - Getting to Know the Pipeline
Suggested Courses

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question