Please provide the diff b/w ref and out parameters in C#
Asked
Active
Viewed 222 times
1
-
Dupe of http://stackoverflow.com/questions/388464/c-whats-the-difference-between-the-ref-and-out-keywords – Anton Gogolev Mar 12 '10 at 09:56
-
possible duplicate of [What is diff Between Ref And OUt??](http://stackoverflow.com/questions/1016601/what-is-diff-between-ref-and-out) – Ruben Bartelink Sep 27 '10 at 07:40
3 Answers
2
A ref parameter:
- has to be initialized by the caller.
- does not have to be assigned in the function.
An out parameter:
- does not have to be initialized by the caller.
- has to be assigned in the function.

Mark Byers
- 811,555
- 193
- 1,581
- 1,452
-
1It should be noted that the CLR treats them both the same and so you cannot have two methods where the only difference in parameters is that one is ref and one is out. – JonC Mar 12 '10 at 10:20
-
2Just to be picky, an out parameter does not have to be assigned in the callee. void M(out int x) { throw new NotImplementedException(); } is perfectly legal, but x is never assigned in the callee. – Eric Lippert Mar 12 '10 at 15:24
2
The difference is that a ref
parameter is for both input and output to the method, while an out
parameter is only for output.
When you call a method with a ref
parameter, it has to have a value before you call the method:
int value = 42;
SomeMethod(ref value);
When you call a method with an out
parameter, it doesn't have to have a defined value before calling the method:
int value;
SomeMethod(out value);
In a method with a ref
parameter, it's known that it has a value, and it doesn't have to be changes:
public void SomeMethod(ref int value) {
int temp = value;
}
In a method with an out
parameter the initial value is not defined, and the value has to be assigned before returning from the method:
public void SomeMethod(out int value) {
value = 42;
}

Guffa
- 687,336
- 108
- 737
- 1,005