Introduction
In C#, either one of 3 keywords must be used when pass by reference:
out
in
ref
out
out refers type parameter is covariant.
out keyword (generic modifier) - C# Reference | Microsoft Learn
out parameter modifier - C# Reference | Microsoft Learn
in
in refers type parameter is contravariant.
Limitation
in parameter modifier - C# Reference | Microsoft Learn
ref
The combination of in and out.
ref keyword - C# Reference | Microsoft Learn
Notice
ref v.s. out
An argument that is passed to a ref or in parameter must be initialized before it's passed. This requirement differs from out parameters, whose arguments don't have to be explicitly initialized before they're passed.
Not Overloading in ref, out, in.
Function or members of a class can't have signatures that differ only by ref
, in
, or out
i.e. It is not allowed to declare two functions with same name that parameters between these with both same type except the modifiers in parameter is not same (one of ref, in, out ). It will cause compiler error.
The following code will cause compiler error.
class CS0663_Example
{
// Compiler error CS0663: "Cannot define overloaded
// methods that differ only on ref and out".
public void SampleMethod(out int i) { }
public void SampleMethod(ref int i) { }
}
It is okay. No Compile Error.
class RefOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}