The more I see ref used in production code, the more misuse I encounter and the more pain it causes me. I have come to hate this keyword, because from a framework-building standpoint, it seems silly. When would it be a good idea to communicate to users of your code the notion of maybe changing an object reference/value out from beneath them?
By contrast, I love out keywords and I love even more when no keywords are used at all, in both cases because of the guarantees you're given when using them. Ref on the other hand makes no guarantees, except that you'll be forced to initialize the parameter before you pass it in, even though nothing may be changed about it.
I'm no sage developer though; I'm sure it's got practically applicable uses. I'd just like to know what they are.
As a middle-level language, C combines the features of both high-level and low-level languages. It can be used for low-level programming, such as scripting for drivers and kernels and it also supports functions of high-level programming languages, such as scripting for software applications etc.
In C/C++, the # sign marks preprocessor directives. If you're not familiar with the preprocessor, it works as part of the compilation process, handling includes, macros, and more. It actually adds code to the source file before the final compilation.
(*) before a variable name means that is a POINTER. We have just seen that a variable which stores a reference to another variable is called a pointer. Pointers are said to "point to" the variable whose reference they store. Using a pointer we can directly access the value stored in the variable which it points to.
iOS, Android and Windows Phone kernels are also written in C. They are just mobile adaptations of existing Mac OS, Linux and Windows kernels. So smartphones you use every day are running on a C kernel.
The Framework Design Guidelines (a book by Krzysztof Cwalina and Brad Abrams) recommend to avoid both ref
and out
parameters.
AVOID using
out
orref
parameters.Using
out
orref
parameters requires experience with pointers, understanding how value types and reference types differ, and handling methods with multiple return values. Also, the difference betweenout
andref
parameters is not widely understood. Framework architects designing for a general audience should not expect users to master working without
orref
parameters.
The Framework Design Guidelines cite the canonical Swap
method as a valid exception:
void Swap<T>(ref T obj1, ref T obj2) { T temp = obj1; obj1 = obj2; obj2 = temp; }
but at the same time a comment remarks
Swap always comes up in these discussions, but I have not written code that actually needed a swap method since college. Unless you've got a very good reason, avoid
out
andref
altogether.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With