C# Error CS1686 – Local ‘{0}’ or its members cannot have their address taken and be used inside an anonymous method or lambda expression

C# Error

CS1686 – Local ‘{0}’ or its members cannot have their address taken and be used inside an anonymous method or lambda expression

Reason for the Error & Solution

Local ‘variable’ or its members cannot have their address taken and be used inside an anonymous method or lambda expression

This error is generated when you use a variable, and attempt to take its address, and one of these actions is done inside an anonymous method.

Example

The following sample generates CS1686.

// CS1686.cs  
// compile with: /unsafe /target:library  
class MyClass  
{  
   public unsafe delegate int * MyDelegate();  
  
   public unsafe int * Test()  
   {  
      int j = 0;  
      MyDelegate d = delegate { return &j; };   // CS1686  
      return &j;   // OK  
   }  
}