1

Please provide the diff b/w ref and out parameters in C#

user282078
  • 969
  • 1
  • 6
  • 7

3 Answers3

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
  • 1
    It 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
  • 2
    Just 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
0

ref must be initialized with default value. No need for out

Sunil
  • 1,941
  • 3
  • 19
  • 25