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

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?


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.


The ref modifier means that:

  • The value is already set and
  • The method can read and modify it.
  • The out modifier means that:

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

  • Let's say Dom shows up at Peter's cubicle about the memo about the TPS reports.

    If Dom were a ref argument, he would have a printed copy of the memo.

    If Dom were an out argument, he'd make Peter print a new copy of the memo for him to take with him.

    链接地址: http://www.djcxy.com/p/12808.html

    上一篇: 投射vs在CLR中使用'as'关键字

    下一篇: 'ref'和'out'关键字有什么区别?