Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Bind to existing variables in patterns #13400

Closed
alrz opened this issue Aug 26, 2016 · 1 comment
Closed

Proposal: Bind to existing variables in patterns #13400

alrz opened this issue Aug 26, 2016 · 1 comment

Comments

@alrz
Copy link
Contributor

alrz commented Aug 26, 2016

Proposal: Bind to existing variables in patterns

Ability to assign the target expression to existing variables (rel. #8990, #9005):

public static bool Member(this Expression @this, out Expression expr, out string memberName) {
  if(@this is MemberExpression { Expression: var exprTemp, Member: { Name: var memberNameTemp } }) {
    expr = exprTemp;
    memberName = memberNameTemp
    return true;
  } else {
    expr = null;
    memberName = null;
    return false;
  }
}

We can rewrite this method in one line if we could assign the target expression to existing variables inside the pattern.

public static bool Member(this Expression @this, out Expression expr, out string memberName) {
  return @this is MemberExpression { Expression: out expr, Member: { Name: out memberName } }
}

That's it. If the pattern-match failed, variables will be assigned to their default value, therefore, they are definitely assigned before leaving the method and no CS0177 shall be raised.

This is specifically useful with #11293 and #13401.

Note: When we are matching against the static type of a property of another property it could be simplified further using the dot operator:

public static bool Member(this Expression @this, out Expression expr, out string memberName) {
  return @this is MemberExpression { Expression: out expr, Member.Name: out memberName }
}

etc.

@alrz alrz changed the title ### Proposal: Bind to existing variables in patterns Proposal: Bind to existing variables in patterns Aug 26, 2016
@HaloFour
Copy link

I agree. With deconstruction following the out parameter route and possibly active patterns as well I think it would make for some succinct one-liners to be able to match and deconstruct directly into existing variables. As pattern variables are no longer readonly I think that the inconsistency concerns are no longer a factor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants