-2

Possible Duplicate:
Difference between ref and out parameters in .NET

What is different between Out type and Ref type parameters in C#.net?


When we can use in which situation?

Community
  • 1
  • 1
Abhishek B.
  • 5,112
  • 14
  • 51
  • 90

2 Answers2

1

Both indicate to the caller that the method can modify the value of the parameter. out parameters must be initialized inside the method whereas ref parameters might be initialized outside. It's basically a contract. When you see a method that takes an out parameter this means that that caller can invoke it without initializing the value and be sure that it will be initialized inside:

Foo foo;
SomeMethod(out foo);
// at this stage we know that foo will be initialized

whereas with ref:

Foo foo;
SomeMethod(ref foo); // compile time error

It's the caller's responsibility to initialize the variable before calling the method:

Foo foo = new Foo();
SomeMethod(ref foo); // ok
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

Quote from here

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.

Some methods, like Int32.TryParse() use a out parameter, so one pass an unitialized variable into it.

Mithrandir
  • 24,869
  • 6
  • 50
  • 66