Grey
Grey

Reputation: 63

Confused about passing by ref/value in c#

As in the title something just hasn't clicked for me yet as i'm still learning c#, the following is some really basic code that i'm using just to get the grasp of it.

    [TestMethod]
    public void Pass()
    {
        int x = 4;
        Increment(x);
        Assert.AreEqual(5, x);
    }
    void Increment(int num)
    {
        num++;
    }

I know that if i add ref in it will work just fine, however I've seen that using that isn't always the best case. What could i do instead of using ref and why?

Upvotes: 1

Views: 200

Answers (2)

Nick Stafford
Nick Stafford

Reputation: 41

[TestMethod] public void Pass() {
    int x = 4;
    x = Increment(x);
   Assert.AreEqual(5, x);
 }

int Increment(int num) {return ++num; }

This should work if your set on not using passing by ref.

Essentially when not passing by ref your giving the called method a copy of the original object. So your changes to it in Increment won't be reflected on the original (unless like here you return the new value from the method and use it in an assignment).

When passing by ref your giving the called method a reference to your original object. In that case any ammendments ARE performed on the original.

Hope that helps.

Upvotes: 1

usr
usr

Reputation: 171246

  1. Don't mutate state in the caller. Return the new int value as the return value. State mutation is to be avoided in general.
  2. Continue to use ref if available. Nothing wrong with it except for the state mutation problem.
  3. Use an object on the heap, for example class IntHolder { int MyInt; } or StrongBox<int> which is built-in.

If you tell us more context we can recommend a specific solution.

Upvotes: 4

Related Questions