C# provides the ref
and the out
keyword to make arguments to be passed by reference. The semantic of the two is very similar. The only difference is in the initialization of the flaged variable:
ref
requires the variable to be initialized before passing it to the function,out
does not.out
requires the variable to be initialized inside the function,ref
does not.
The use cases of these two keywords are also almost the same, and their too frequent usage is I beleive considered a code smell (although there are valid use cases like the TryParse
and TryGetValue
patterns).
Because of this could someone explain, why there are two very similar tools in C# for so narrow use cases?
Also, on MSDN, it is stated that they have different run-time behavior:
Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time.
How is their run-time behavior different?
Conclusion
Both answers looks correct, thank you both. I accepted jmoreno's because it is more explicit.
ref
in C++; to pointers to the object pointer (or primitive) in question. i.e.Int32.TryParse(myStr, out myInt)
(C#) is "executed" the same way asint32_tryParse(myStr, &myInt)
(C) would; the only difference being some constraints enforced by the compiler to prevent bugs. (I'm not gonna post this as an answer because I may be wrong about how this works behind the scenes, but this is how I envision it works [because it makes sense])