+ 1
What's the practical difference between out and ref?
I understand the difference between using ref and out for methods, however I still can't see a real world difference in usage. Can someone provide a practical example of how accomplishing a certain task would require or benefit primarily from using a reference instead of out or visa versa?
3 Réponses
+ 3
The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. For example:
class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
} }
The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method. For example, if the caller passes a local variable expression or an array element access expression, and the called method replaces the object to which the ref parameter refers, then the caller’s local variable or the array element now refer to the new object.
To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword, as shown in the following example.
C#
class RefExample
{
static void Method(ref int i)
{
// Rest the mouse pointer over i to verify that it is an int.
// The following statement would cause a compiler error if i
// were boxed as an object.
i = i + 44;
}
static void Main()
{
int val = 1;
Method(ref val);
Console.WriteLine(val);
// Output: 45
}
}
+ 1
There's a newly-added feature that allows you to use out var:
Here's how the function would look like:
static void Function(int a, out int i)
{
// do something
}
You can call it from main() like this:
static void Main(string[] args)
{
int a = 37;
Function(a, out var b);
}
0
Thanks for responding. From what I can see the only difference is that ref requires the variable to be initialized. Does this mean that when using the out function, the value is not passed?
class test
{
static void Method(out int i)
{
//Would this cause an error?
i = i + 3;
}
static void Main()
{
int val = 1;
Method(out val);
Console.WriteLine(val);
}
}
Would the above sample cause an error? If so it helps me answer the question. I still don't see however any possible code that uses the out function that you could just use ref to accomplish the same thing anyway. So what's the point of having the out function?