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.
With the risk of sounding mean, you should read the C# reference :)
C# divides things into reference types and value types. Reference types are as you can imagine, being passed by reference. This means a reference to the object is passed.
Here is a contrived example of return by reference:
class MyClass // <- Reference type.
{
private MyClass _child = new MyClass();
public MyClass GetChild()
{
return _child;
}
}
Value types are passed by value; although I imagine under the hood something else could be going on. This is not important to you though, only the behaviour is important.
Example of value types: , int, char...Color
You create a reference type through , and a value type through class.struct
You cannot. If you want to pass a parameter by reference, the method should have a ref in its definition.
For example
static void Mymethod(ref int i)
can be called by
int localvariable = 5;
Mymethod(ref localvariable);
but your method definition cannot be
static void Mymethod(int i)
This will create new list and it will replace variable from outside:list
public void Foo(ref List<string> myList)
{
myList = new List<string>();
}
This will not replace variable from outside:list
public void Foo(List<string> myList)
{
myList = new List<string>();
}
Short answer: read my article on argument passing.
Long answer: when a reference type parameter is passed by value, only the reference is passed, not a copy of the object. This is like passing a pointer (by value) in C or C++. Changes to the value of the parameter itself won't be seen by the caller, but changes in the object which the reference points to will be seen.
When a parameter (of any kind) is passed by reference, that means that any changes to the parameter are seen by the caller - changes to the parameter are changes to the variable.
The article explains all of this in more detail, of course :)
Useful answer: you almost never need to use ref/out. It's basically a way of getting another return value, and should usually be avoided precisely because it means the method's probably trying to do too much. That's not always the case ( etc are the canonical examples of reasonable use of TryParse) but using ref/out should be a relative rarity.out
Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:
public delegate double MyFunction(double x);
public double Diff(double x, MyFunction f)
{
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
public double MyFunctionMethod(double x)
{
// Can add more complicated logic here
return x + 10;
}
public void Client()
{
double result = Diff(1.234, x => x * 456.1234);
double secondResult = Diff(2.345, MyFunctionMethod);
}