Given that out and ref parameters have slight different connotations would writing code like below be considered a bug (even though it doesn’t cause an issue at present), or just a lack of understanding on ref and out parameters?
public void MyMethod()
{
int myInt = 0;
MyMethodWithRef(ref myInt);
}
public void MyMethodWithRef(ref myInt)
{
// not used before being assigned a value. Does an out parameter make more sense then
myInt = 5;
}
I understand that this is the incorrect usage of ref but if you saw that in code constantly or even once would you consider it a bug and hence fix it as well as inform the original coder or just do it as part of general refactoring practices?
3
It’s not a bug in that the compiler won’t flag it and given the existing code base, it will not cause a difference in behavior.
It is an issue that would be brought up in a code review or interview — it is imprecise, it makes the next programmer ask “why”, which if not a mortal sin is at least a venial sin. Is it left over from a copy/paste code reuse, a half implemented feature, part of an incomplete bug fix — which way, changing from out to ref or vice-a-versa, is it necessary and I’m just not seeing it, is it a terrible mistake by someone that didn’t know better and am I not seeing that….
Although I generally approve of extra restrictions, I’m not convinced that in practice this is a useful syntax — that said, the language does make the distinction, and there’s a cost to not following conventions. Not in terms of performance or scale, but in readability and maintainability.
2
From the C# documentation.
An argument that is passed to a ref parameter must be initialized before it is passed. This differs from out parameters, whose arguments do not have to be explicitly initialized before they are passed
The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed.
The ref and out keywords are treated differently at run-time, but they are treated the same at compile time.
I think that explains it well.
If you need the method to be passed a value, then use ref. If you need the method to just output a value, then use out. You shouldn’t use out if you expect the parameter of the method to contain a value already.
Your example is not a bug, because the compiler imposes this restriction. A ref can output a result. That is not it’s requirement. The requirement is that it has been initialized.
It would be a bug if you expected out to already contain a value.
Yes, an out makes more sense in that case. It will be more readable as to intent.
In your example, I would change your return type from void
to int
, declare myInt
local to the method, then return
it at the end.
1