Pregunta

In C#.NET Can anybody tell me a reason to use reference parameters (such as ref, out) instead of using a global variable? As I can see everything can be handled easily by using just a global variable where we have to use the same variable value in different functions. So I can't think about a situation where we have the only option to use reference parameters instead of Global variables. I would be glad if you can give me a scenario where it happens. Thanks in advance.

¿Fue útil?

Solución

Its just bad programming!

Say you finished working on your program and then a month later you want to come back and add another features. But you accidentally used in that global variable inside your new class.

Now it changes stuff in another classes that your don't want to change. And you have many more bugs and you have no idea where to begin because you didn't touch the code for a month.

And one more thing about the ref word - one of its goals is to force your initialize the variable before you return it. That way the compiler makes sure that you don't use variable containing garbage which will crush the code. When you use a global variable you can use in that uninitialized global variable and you'll get an exception.

So if you know when and how to use ref and out - use them.

And don't EVER use global variable. bad programming.

Good luck!

Otros consejos

Global variables and parameter modifiers have very little in common. First of all the closest you can get to a global variable in C# is using a public static field.

Parameter modifiers change the way method parameters are treated. An out parameter is like an additional return variable, it receives its value in the method and the compiler guarantees that. A ref parameter is used for both input and output. It can be modified inside the method but it doesn't have to.

A global variable is just like any other variable, except that it can be accessed from anywhere and that there is only one instance of it.

Of course a global variable can be used to achieve similar behaviour as a parameter modifier, but only at a first glance. Unlike an out parameter the compiler won't guarantee that you assign a value to it. It is harder to use, maintain and document and maybe most importantly it will fail completely in a multithreaded environment unless you spend a lot of additional work making access to the variable thread-safe.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top