1

How to pass a parameter as a Reference in C# and when calling the function how should i represent it while defining that particular function

itsmatt
  • 31,265
  • 10
  • 100
  • 164
subbu
  • 3,229
  • 13
  • 49
  • 70
  • 6
    Related question: http://stackoverflow.com/questions/135234/difference-between-ref-and-out-parameters-in-net – itsmatt Oct 26 '09 at 12:30
  • 1
    Wouldn't it have been quicker to just search MSDN than post a question here and wait for the answer: http://social.msdn.microsoft.com/search/en-ca/?query=Pass+by+Reference – Philip Wallace Oct 26 '09 at 12:55

6 Answers6

11

As others have said, you should use the ref modifier at both the call site and the method declaration to indicate that you want to use by-reference semantics. However, you should understand how by-value and by-reference semantics interact with the "value type" vs "reference type" model of .NET.

I have two articles on this:

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
9

Here's an example of passing an int by reference:

void DoubleInt(ref int x)
{
    x += x;
}

and you would call it like this:

DoubleInt(ref myInt);  

Here's an msdn article about passing parameters.

Joseph
  • 25,330
  • 8
  • 76
  • 125
4

You can use the ref keyword to pass an object by refence.

public void YourFunction(ref SomeObject yourReferenceParameter)
{
    // Do something 
}

When you call it you are also required to give the ref keyword.

SomeObject myLocal = new SomeObject();

YourFunction(ref myLocal);
David Basarab
  • 72,212
  • 42
  • 129
  • 156
2

I suggest you take a look at the MSDN documentation about this. It's very clear.

Martin Marconcini
  • 26,875
  • 19
  • 106
  • 144
0

Just add ref keyword as prefix to all arguments in the function definition. Put ref keyword prefix in arguments passed while calling the function.

this. __curious_geek
  • 42,787
  • 22
  • 113
  • 137
0

you can also reference types without need to user ref keyword
For example you can bass an instance of Class to a method as a parameter without ref keyword

Amr Badawy
  • 7,453
  • 12
  • 49
  • 84