Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I need to use ref keyword in both declaration and Call?

Tags:

c#

keyword

ref

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 ?

like image 799
MRG Avatar asked Oct 06 '09 07:10

MRG


People also ask

What is the difference between the call by reference keywords out and ref?

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.

Why do we need ref and out in C#?

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.

What is the use of ref keyword?

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.

What is the difference between the ref and out keywords Linkedin?

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.


2 Answers

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?

like image 151
Graviton Avatar answered Oct 23 '22 14:10

Graviton


It enhances readability/understandability: When you look at the method call, you know that the ref value might change.

like image 32
Lennaert Avatar answered Oct 23 '22 15:10

Lennaert