Search code examples
c#oopobjectvalue-typereference-type

Is object a reference type or value type?


I have still doubts about object. It is the primary base class of anything, any class. But is it reference type or value type. Or like which of these acts it? I need to get this clarified. I have difficulty understanding that.

     object obj1 = "OldString";
     object obj2 = obj1;
     obj1 = "NewString";
     MessageBox.Show(obj1 + "   " + obj2);
     //Output is  "NewString   OldString" 

In this case it acts like a value type. If object was reference type then why obj2 value is still "OldString"

   class SampleClass
    {
        public string Text { get; set; }
    }

    SampleClass Sample1 = new SampleClass();
    Sample1.Text="OldText";         

    object refer1 = Sample1;
    object refer2 = refer1;

    Sample1.Text = "NewText";

    MessageBox.Show((refer1 as SampleClass).Text +  (refer2 as SampleClass).Text);
    //OutPut is "NewText   NewText"   

In this case it acts like reference type

We can deduce that object's type is what you box inside it. It can be both a reference type and value type. It is about what you box inside. Am I right?


Solution

  • It is a reference type

    Doing an example with string isn't very illuminating, because string is also a reference type (as is SampleClass, obviously); your example contains zero "boxing".

    if object is reference type then why obj2 value is still "OldString"

    Why wouldn't it be? When you create a new string, that doesn't change old references to point at the new string. Consider:

     object obj1 = "OldString";
     // create a new string; assign obj1 the reference to that new string "OldString"
    
    object obj2 = obj1;
     // copy the reference from obj1 and assign into obj2; obj2 now refers to
     // the same string instance
    
     obj1 = "NewString";
     // create a new string and assign that new reference to obj1; note we haven't
     // changed obj2 - that still points to the original string, "OldString"