EmeraldCube
EmeraldCube

Reputation: 27

Why doesn't boxing and unboxing work with methods?

class Program
{
  public static void FunnyMethod(object a)
  { a = 5; }
  public static void NotSoFunnyMethod(int a)
  { a = 5; }

  public static void main(string[] args)
  {
    int number = 10;
    object obj = number;

    FunnyMethod(obj);
     Console.WriteLine(obj);

    NotSoFunnyMethod((int)obj);
    Console.WriteLine(obj);
  }
}
output : 10 in both cases

Basically I'm a little curious. When you create an object instance and try to work with it outside the scope of the main method, it doesn't return the final value(5) through the other methods even though it's a reference type object.

Why is that?

Upvotes: 0

Views: 70

Answers (2)

Arcord
Arcord

Reputation: 1919

If the int was a property of an object this would work (because both reference would point to the same object in the heap).

Int (even as an object) is immutable (like string) so with "a = 5" you just create a new object and erased the reference of your parameter. (But the calling code still have the previous reference).

You can do what you want with the "ref" keyword :

    public static void FunnyMethod(ref object a)
    { a = 5; }
    public static void NotSoFunnyMethod(int a)
    { a = 5; }

    public static void Main(string[] args)
    {
        int number = 10;
        object obj = number;

        FunnyMethod(ref obj);
        Console.WriteLine(obj);

        NotSoFunnyMethod((int)obj);
        Console.WriteLine(obj);
    }

Upvotes: 1

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30235

I guess it has nothing to do with boxing, it will behave the same way for objects as well.

When you pass a reference to a method, it cannot be changed in that method. It's because of parameters being passed by value, you can change it to reference though.

You can use the ref keyword to get 5 in both cases.

Upvotes: 1

Related Questions