.NET Tips and Tricks

Blog archive

Changing Parameter Values with out and ref

By default, any values that you pass to a method in a parameter are protected from change inside the method. In this code, for example, I know that my variable NotChanged can't be different after I call the method. In this code, the test on the last line is guaranteed to be true:

string NotChanged;
NotChanged = "Fred";
if (NotChanged == "Fred") ...

That is, unless the parameters to the method are marked with the ref keyword, as in this example:

void MyRefMethod(ref string parm1)

Now, if I call this method the value of anything that I pass to that first parameter could be different after calling the method. To make sure that I realize that possibility, the compiler also requires that the calling code use the ref keywords. In this code, the test on the last line is not guaranteed to be true and, thanks to having to provide the ref keyword, I know that:

string PossiblyChanged;
PossiblyChanged = "Fred";
MyRefMethod(ref res);
if (PossiblyChanged == "Fred") ...

While a parameter marked with the ref keyword may or may not be changed, the out keyword is more definite: The out keyword indicates that code inside the method will always change the value in the parameter. If you mark a parameter as out and there is a path through your method that doesn't alter the value of the parameter then the compiler will generate an error.

In addition, with the out parameter, the compiler will refuse to compile your method if, inside your method, you attempt to use the out parameter without first setting its value. In other words, when calling a method with an out parameter, the calling code can set the value of the parameter before passing it to the method -- but it won't do a bit of good because the method has to override that value before it can use the parameter. Again, because I have to use the out parameter when calling the method, I know that:

string DefinitelyChanged;
MyRefMethod(out DefinitelyChanged);
if (DefinitelyChanged == "Fred") ...

That's it for now, I'm out.

Posted by Peter Vogel on 05/05/2016 at 9:37 AM

comments powered by Disqus
Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.