C# Error
CS1741 – A ref or out parameter cannot have a default value
Reason for the Error & Solution
A ref
or out
parameter cannot have a default value
Using ref
or out
in a method signature causes arguments to be passed by reference, making the parameter an alias for the argument. Since the parameter must be a variable should the default value be used, no variable would exist as the alias for the argument.
Example
The following sample generates CS1741:
// CS1741.cs (6,21)
class Program
{
static void Main(string[] args)
{
void RefOut(ref int x = 2)
{
x++;
}
int y = 2;
RefOut(ref y);
}
}
To correct this error
In this example, removing the ref
modifier from the method signature would be a logic error–the method’s body would have no visible side effects when executed. To correct this error, remove the unnecessary default value from the method signature:
static void Main(string[] args)
{
void RefOut(ref int x)
{
x++;
}
int y = 2;
RefOut(ref y);
}