What's the difference between the 'ref' and 'out' keywords?


Question

I'm creating a function where I need to pass an object so that it can be modified by the function. What is the difference between:

public void myFunction(ref MyClass someClass)

and

public void myFunction(out MyClass someClass)

Which should I use and why?

1
833
11/8/2012 2:02:50 AM

Accepted Answer

ref tells the compiler that the object is initialized before entering the function, while out tells the compiler that the object will be initialized inside the function.

So while ref is two-ways, out is out-only.

1101
12/21/2012 1:54:43 PM

The ref modifier means that:

  1. The value is already set and
  2. The method can read and modify it.

The out modifier means that:

  1. The Value isn't set and can't be read by the method until it is set.
  2. The method must set it before returning.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon