C# Error CS1065 – Default values are not valid in this context.

C# Error

CS1065 – Default values are not valid in this context.

Reason for the Error & Solution

Default values are not valid in this context.

Default values are used when declaring optional arguments. Optional arguments are not supported when declaring an anonymous method with the delegate operator. The delegate operator creates an anonymous method.

Example

The following sample generates CS1065:

// CS1065.cs (5,27)

class A
{
    delegate void D(int x);
    D d1 = delegate(int x = 42) { };
}

To correct this error

Removing the default value corrects this error:

class A
{
    delegate void D(int x);
    D d1 = delegate(int x) { };
}