Pass by Reference in C#
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
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:
- Parameter passing in C#
- Reference types and value types
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.
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);
I suggest you take a look at the MSDN documentation about this. It's very clear.
Just add ref keyword as prefix to all arguments in the function definition. Put ref keyword prefix in arguments passed while calling the function.
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
精彩评论