0

First time post. I am by no means a "new" programmer, I have over 12 years experience, however I've just come across something which I'm not sure how or why it works and never really thought to ask about it until now.

Now I understand the differences of passing by Value and passing By Reference, but I seem to have been writing code for years which seems to break this theory.

So for instance I have the following:

public static void MyRoutine()
{
    objMyObject obj = new objMyObject();
    DoSomething(obj);
}

protected static void DoSomething(objMyObject obj)
{
    obj.ID = 1;
}

So passing the object By Value above, I am allowed to modify it. However if I do something like this:

public static void MyRoutine()
{
    int obj = int.MinValue;
    DoSomething(obj);
}

protected static void DoSomething(int obj)
{
    obj = 1;
}

The object passed in By Value behaves as should and the modifications aren't reflected when we return to the main procedure.

Now the only think that I can think of is that in my first example, I'm passing an object from an object I've created myself and what I'm actually doing is modifying the properties of the object and not the object itself, meaning when passing by value, you can modify the properties of an object, but not the object itself.

Is that the correct and if not can anyone please offer a solution as to explain this scenario.

Many Thanks In Advance

Nick Scotney
  • 269
  • 1
  • 2
  • 11
  • see jon skeet's summary: http://stackoverflow.com/a/8708674/1160796 – basher Jun 09 '15 at 14:38
  • 3
    In your first example `obj` _is_ a reference (akin to a pointer in C++) that's passed by value. Only parameters prefaced by `ref` or `out` are _truly_ passed by reference. – D Stanley Jun 09 '15 at 14:38
  • And in your second example, since you are passing by value but the modification to that value is never returned from your method, the original scope isn't modified. To the contrary, if you "ref"'d your int obj parameter, of course it would be updated. – David L Jun 09 '15 at 14:39
  • Yeah. Read the skeet link. If you think in unmanaged code, think of passing "by reference" as passing a pointer: it's a reference to some memory but you can still overwrite it with the value of another pointer. – Nathan Cooper Jun 09 '15 at 14:40
  • 3
    It can be very confusing, but pass-by-reference / pass-by-value is a different concept than reference types / value types. – Dennis_E Jun 09 '15 at 14:40
  • Thanks for the replies and link guys. So in my first example it works because I'm changing the data within the object that is being passed. I knew the 2nd didn't work because of the lack ok [code](ref) declaration next to the parameter. Thanks Again Guys – Nick Scotney Jun 09 '15 at 15:50

0 Answers0