I am adding this answer for programmers that are used to C++ like myself.
Classes, interfaces, delegatess and arrays are reference types
, meaning that they have an underlying pointer. Normal function calls copy this pointer(reference) by value, while sending by reference sends sends a reference to this reference:
//C# code:
void Foo(ClassA input)
void Bar(ClassA ref input)
//equivalent C++ code:
void Foo(ClassA* input)
void Bar(ClassA*& input)
Primitives such as int, double, etc structs and strings(string are an exception to these, but works similar), are allocated on the heap, so things work a bit different:
//C# code:
void Foo(StructA input)
void Bar(StructA ref input)
//equivalent C++ code:
void Foo(StructA input)
void Bar(StructA& input)
the ref
keyword needs to be used both in declaration of the method and when calling it, so it would be clear it is referenced:
//C# code:
void Foobar(ClassB ref input)
...
ClassB instance = new ClassB();
Foobar(ref instance);
//equivalent C++ code:
void Foobar(ClassB*& input)
...
ClassB instance* = new ClassB();
Foobar(instance);
As said before, please read this detailed explanation. It also explains about strings.
It is interesting to note that calling by reference works with an underlying pointer, so we get to this code:
//C# code:
void Foo(ClassA input){
input = input + 3;
}
void Bar(ClassA ref input){
input = input + 3;
}
//equivalent C++ code:
void Foo(ClassA& input){
input = input + 3;
}
void Bar(ClassA*& input){
*input = *input + 3;
}
//equivalent pure C code:
void Fun(ClassA* input){
*input = *input + 3;
}
void Fun(ClassA** input){
*(*input) = *(*input) + 3;
}
it's a rough equivalent, but it's somewhat true.