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,335,956
- 823
- 8,931
- 9,049
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.
- 24,926
- 8
- 74
- 123
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);
- 70,191
- 42
- 128
- 155
I suggest you take a look at the MSDN documentation about this. It's very clear.
- 25,191
- 19
- 103
- 139
Just add ref keyword as prefix to all arguments in the function definition. Put ref keyword prefix in arguments passed while calling the function.
- 41,911
- 22
- 111
- 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,153
- 12
- 47
- 83