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
-
6Related question: http://stackoverflow.com/questions/135234/difference-between-ref-and-out-parameters-in-net – itsmatt Oct 26 '09 at 12:30
-
1Wouldn'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 Answers
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:

- 1,421,763
- 867
- 9,128
- 9,194
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.

- 25,330
- 8
- 76
- 125
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);

- 72,212
- 42
- 129
- 156
I suggest you take a look at the MSDN documentation about this. It's very clear.

- 26,875
- 19
- 106
- 144
Just add ref keyword as prefix to all arguments in the function definition. Put ref keyword prefix in arguments passed while calling the function.

- 42,787
- 22
- 113
- 137
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

- 7,453
- 12
- 49
- 84