Difference between ref and out in .net

July 28th, 2009 admin Posted in asp.net, c#, development | No Comments »

There are a couple of ways getting output parameters from .net procedures: you can use the keyword out or the keyword ref. Like so:

public void DoSmth(ref int nRefVar){}


public void DoSmth(out int nOutVar){}

What's the difference? Well, that's pretty easy. To pass a variable by reference, first you have create that reference by initializing the variable. Usually you want to use this way when you're gonna use the value of the variable inside the function.

public void DoSmth(ref int nRefVar)
if (nRef > 10)
nRef = 5;
nRef = 25;
int nRefVar = 10;
DoSmth(ref nRefVar);

To pass a variable as an out parameter you have only to declare it first. This way is just for getting the value. Usually you will need it when you have to get more than one return value from a procedure.

public void DoSmth(out int nOutVar1, out int nOutVar2)
nOutVar1 = 1;
nOutVar2 = 2;
int nOutVar1, nOutVar2;
DoSmth(out nOutVar1, out nOutVar2);

Good Luck

Leave a Reply

You must be logged in to post a comment.