Differentiate between out and ref keywords


The out keyword causes arguments to be passed by reference, which is similar to the ref keyword, except that ref requires that the variable be initialized before being passed.

This means inside your method implementation which takes an out parameter you have to set a value before you can use it. At least you have to assign a value before you can return. 

This also means you can not use the out parameter to pass a value to the method. (With ref you can).


This also means you can not have any logically includes comparison (e.g. if (param > 0) {...}) inside your method before you assign a value to your incoming parameter.


"The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument."

To see the difference in IL, you can use Reflector to see how the IL looks like for out/ref on Value Types (in my case int32):
out: [out] int32& result
ref: int32& result

Remarks:
- Most of the Framework functions (e.g. TryParse) use out and not ref. But inside the internal implementation the Framework mainly uses ref.
- Properties can not be passed via out or ref. (Under the hood they are function calls)
- It is very handy if you have several Value Types as return values and you don't want to create a class or struct.

No comments:

Post a Comment