C# Error CS1741 – A ref or out parameter cannot have a default value

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);
    }

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...