Why can’t you use a ref or out parameter in a lambda expression?

I came across the error today and found a workaround but I was still curious why this is a compile-time error.

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

Here’s a simple example:

private void Foo()
{
    int value;
    Bar(out value);
}

private void Bar(out int value)
{
    value = 3;
    int[] array = { 1, 2, 3, 4, 5 };
    int newValue = array.Where(a => a == value).First();
}

5 Answers
5

Tags:

Leave a Reply

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