(As mentioned, this is a dupe of this question.)
For one thing, it's used as part of method overloading:
public void Foo(string x) { ... }
public void Foo(ref string x) { ... }
...
string x = "";
Foo(x); // Which should be used if you didn't have to specify ref?
Now one answer could be to prohibit that sort of overloading... but I think it's a good thing for C# to require this at the caller's side as documentation:
- The behaviour changes significantly when you use
ref
(or out
)
- By calling out the rare uses of ref/out, it means you never need to check whether
the argument is being passed by value or reference
- It also affects what you can pass (e.g. you can't pass a literal, or the result of a method call). This is clearer when it's explicit.
Note that C# 4 does allow implicit use of ref
for COM methods as there are so many ref
parameters which don't really have ref
behaviour (or at least, they don't take advantage of it). In such cases the compiler introduces a new local variable so that from the caller's point of view the argument really is being passed by value:
ComMethod(x);
translates into:
MyType tmp = x;
ComMethod (ref tmp);
This is a good compromise for COM methods, but I'm glad it's not the case for normal managed code.