Why do I need to use the ref keyword in a declaration and call?

Duplicate: What is the purpose of the out keyword for the caller?

Why I need to use the keyword 'ref' in a declaration and call.

void foo(ref int i)
{

}

For example, consider the function above. If I call him without the ref keyword

foo(k);

he will give me an error:

The argument '1' must be passed using the keyword 'ref'

Why is it not enough to just indicate only in the method signature?

+5
source share
6 answers

, ref , . - ++

:

void CalFoo()
{
  var i=10;
  foo(ref i);  //i=11
}
void foo(ref int i)
{
   i++;
}

void CalFoo()
{
  var i=10;
  foo(i);  //i=10
}
void foo(int i)
{
   i++;
}

, foo(ref int), foo(int) . , ref.. , ?

+11

/: , , ref .

+8

( , .)

, :

public void Foo(string x) { ... }
public void Foo(ref string x) { ... }

...

string x = "";
Foo(x); // Which should be used if you didn't have to specify ref?

, ​​... , # , :

  • ref ( out)
  • ref/out, , ,
  • , (, ). , .

, # 4 ref COM-, ref, ref (, , ). , :

ComMethod(x);

:

MyType tmp = x;
ComMethod (ref tmp);

COM, , .

+4

"" ( , , ), . - , , , .

+3

ref , - , . :

string hello = "world";
MyMethod(ref hello);
Console.WriteLine(hello);

ref , , "", .

+3

I also heard (or read somewhere - perhaps in an interview with the language developers) that the reason (as for many other "functions" in C #) is to remind the programmer that use the function that he performs to call argument by reference.

+1
source

All Articles