2

C# 7.2 added readonly structs and the in modifier for method parameters. However, you get a compiler error when you try to use these structs with reference-like semantics in lambda expressions:

public readonly struct Point {
    public Struct(int x, int y) {
        X = x;
        Y = y;
    }
    public int X { get; }
    public int Y { get; }
}

public IEnumerable<Point> FindMatching(
    this IEnumerable<Point> points, 
    in Point toMatch) {
    return point.Where(p => p.X == point.X && p.Y == point.Y);
}

Compiling returns an error:

error CS1628: Cannot use ref or out parameter 'toMatch' inside an anonymous method, lambda expression, or query expression.

It's not a ref or out parameter, however.

9
  • 4
    @Servy I disagree with that dup; it isn't asking why we can't use ref/out here. It is asking specifically about a C# 7.2 feature, so an answer from 2009 cannot possibly answer this directly Commented Feb 1, 2018 at 14:22
  • 2
    @Servy I fundamentally disagree with you here Commented Feb 1, 2018 at 14:25
  • 1
    @MarcGravell How do you think the duplicate fails to answer the question? What about it doesn't answer the question? Commented Feb 1, 2018 at 14:26
  • 2
    @Servy because that question explains why you can't use ref / out in a lambda. The answer to "why does it complain about ref / out when I use in" is simply: because in is actually a ref. Pointing to that answer simply doesn't answer that. Especially given that the compiler message is very confusing and doesn't help here. I'd agree that they're strongly related questions, but they're not the same. Commented Feb 1, 2018 at 14:28
  • 1
    The question states an error message and doesn't ask any question. We're left to infer whether the question is why an error is generated at all, or why that error is generated. Whether closing as a duplicate is correct depends on that. Commented Feb 1, 2018 at 14:33

1 Answer 1

4

Behind the scenes, in is a ref parameter, but with fancy semantics. The same as out is a ref parameter with fancy semantics. The compiler message could be clearer, perhaps - that might be a good bug to log on the Roslyn github. But: it is correct to error. I would agree that the error should explicitly mention in parameters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.