Reputation: 63
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
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
Reputation: 171246
int
value as the return value. State mutation is to be avoided in general.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