Duplicate of: What is the purpose of the “out” keyword at the caller?
Why I need to use 'ref' keyword in both declaration and Call.
void foo(ref int i)
{
}
For example, Consider above function. If I will call it without ref keyword as
foo(k);
it will give me error :
Argument '1' must be passed with the 'ref' keyword
Why isn't it enough to just specify in the method signature only ?
No. ref keyword is used when a called method has to update the passed parameter. out keyword is used when a called method has to update multiple parameter passed. ref keyword is used to pass data in bi-directional way.
ref is used to state that the parameter passed may be modified by the method. in is used to state that the parameter passed cannot be modified by the method. out is used to state that the parameter passed must be modified by the method.
The ref keyword indicates that a variable is a reference, or an alias for another object. It's used in five different contexts: In a method signature and in a method call, to pass an argument to a method by reference.
The ref and out keywords both use the concept of Pass by Reference with data, but with some compiler restrictions. You can think ref keyword as two way where data passed from caller to callee and back while out keyword is a one way, it sends data from calle to caller and any data passed by a caller is discarded.
This is because ref
indicates that the parameter should be passed in by reference. It is something like pointer in C++
For example;
void CalFoo()
{
var i=10;
foo(ref i); //i=11
}
void foo(ref int i)
{
i++;
}
but
void CalFoo()
{
var i=10;
foo(i); //i=10
}
void foo(int i)
{
i++;
}
I think you can have both foo(ref int)
and foo(int)
in one single class. So if you don't specify the ref
.. how does the compiler knows which one to call?
It enhances readability/understandability: When you look at the method call, you know that the ref value might change.
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