-1

I am studying reference and value types in C#. According to documentation string and object are reference types. When we execute following code:

 static void Main(string[] args)
    {
        int a = 30;
        object o = a;
        AlterObject(o);

        Console.WriteLine(o);
        Console.Read();
    }

    static void AlterSObject(object testO)
    {
        int b = 130;
        testO = b;
    }

It prints output as 30. Please explain if object is reference type, why value of object is not changed in function.

AkshayP
  • 188
  • 3
  • 11
  • Because the function doesn't change anything on the object referenced by the `testO` variable. It changes the variable to point to a new reference. Had you done something like `testO.SomeProperty = "some value";` then that property would have changed on the referenced object. – David Nov 07 '18 at 14:19
  • 1
    I can´t see where you use a string. Ths 3 of the 4 duplicates don´t match the question, IMHO. – MakePeaceGreatAgain Nov 07 '18 at 14:36

2 Answers2

2

When you pass the value 30 as object, you create a new instance which points to 30 (this is called boxing), which you pass to the method.

This reference itself is passed - as every argument in .NET - by value. Thus you can´t change the reference, but only its fields or properties. You could re-reference any other object within your method, but because the parameter is still passed by value this won´t be reflected in the calling code.

But even by using the ref-keyword a won´t change, because it has nothing to do with the boxed object:

static void AlterSObject(ref object testO)
{
    int b = 130;
    testO = b;
}

Now o (which is the boxed object and has nothing to do with a) would reflect whatever you assigned to testO within AlterSObject. However a will not reflect it. See my fiddle for test.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • If I create 2 objects like following - object o = 30; object o2 = o; o = 60; Why o and o2 does not share a memory location ? – AkshayP Nov 07 '18 at 14:48
  • 1
    @AkshayP Because you don´t *modify* the underlying object (`30`) , but just reference **another one** (`60`). So `o2` still points to the exact same instance (`30`). – MakePeaceGreatAgain Nov 07 '18 at 14:51
0

You never declared AlterObject()'s parameters as references, so its passing by value. C# will use a pass-by-value approach unless you designate the given parameter as a reference using the ref keyword. You will also need to either overload(as I did in the following sample code) or rewrite your method to accept reference values.

public class test{
static void Main(string[] args){
    int a = 30;
    object o = a;

    AlterObject(ref o);

    System.Console.WriteLine(o);
    System.Console.Read();
}

static void AlterObject(object testO){
    int b = 130;
    testO = b;
}

static void AlterObject(ref object testO){
    int b = 130;
    testO = b;
}
}