C# Error CS1628 – Cannot use ref, out, or in parameter ‘{0}’ inside an anonymous method, lambda expression, query expression, or local function

C# Error

CS1628 – Cannot use ref, out, or in parameter ‘{0}’ inside an anonymous method, lambda expression, query expression, or local function

Reason for the Error & Solution

Cannot use in ref or out parameter ‘parameter’ inside an anonymous method, lambda expression, or query expression

This error occurs if you use an in, ref, or out parameter inside an anonymous method block. To avoid this error, use a local variable or some other construct.

The following sample generates CS1628:

// CS1628.cs  
  
delegate int MyDelegate();  
  
class C  
{  
  public static void F(ref int i)  
  {  
      MyDelegate d = delegate { return i; };  // CS1628  
      // Try this instead:  
      // int tmp = i;  
      // MyDelegate d = delegate { return tmp; };  
  }  
  
  public static void Main()  
  {  
  
  }  
}  

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...