By Value and By Refernece in C#

118 views Asked by At

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

0

There are 0 answers