csharplang icon indicating copy to clipboard operation
csharplang copied to clipboard

Champion: allow 'default' in deconstruction

Open jcouv opened this issue 8 years ago • 5 comments

Allow (int i, string s) = default; and (i, s) = default.

  • [ ] Proposal added
  • [ ] Discussed in LDM (by email so far)
  • [ ] Decision in LDM
  • [ ] Finalized (done, rejected, inactive)
  • [ ] Spec'ed

Initially raised in https://github.com/dotnet/csharplang/issues/1358 (thanks @KnorxThieus) Prototype in decon-default branch

jcouv avatar Mar 17 '18 21:03 jcouv

This will be super nice to do in constructors:

class MyClass
{
    int foo;
    string bar;
    byte baz

    public MyClass() => (foo, bar, baz) = default;
}

AustinBryan avatar Jun 11 '18 14:06 AustinBryan

@AustinBryan Those fields are already zero-inited, so what is the purpose of that constructor?

jnm2 avatar Jun 11 '18 15:06 jnm2

The use case I had in mind for this is assigning a bunch of out parameters on a failure case,

bool TryGet(out int i, out double d) {
  // ...
  (i, d) = default;
  return false;
}

btw I think this is already implemented by jcouv, why the Any Time milestone?

alrz avatar Sep 12 '19 00:09 alrz

The implementation I have is not quite complete because we've recently implemented more target-typing scenarios (switch expressions in particular). So (i, d) = expr switch { true => (1, null); _ => throw null; }; should work too (ie. giving the tuple in branch a type).

jcouv avatar Sep 12 '19 21:09 jcouv

Taking some time into the code regarding this case, and a side-effect would have to also be matching the individual types of the tuple expression:

(1, default)
(default, "")
(1, null)

should match as (int, string), whereas

(1, default)
(null, "")

should match as (int?, string).

I'm awaiting for a response on whether it's okay to follow this approach in another branch targeting the features/decon-default branch, which could be considered a relevant but different feature.

Rekkonnect avatar Jul 08 '22 20:07 Rekkonnect

@jcouv are there any updates on this moving forward? #1358 is still in the Working Set, and the only scenario that I believe was indeed left is the target typing from switch expressions.

Rekkonnect avatar Jul 24 '23 08:07 Rekkonnect