0

I came across this code:

    private class Node
    {
        public Node(T t) => (Next, Data) = (null, t);

        public Node Next { get; set; }
        public T Data { get; set; }
    }

Can someone explain what this means in the constructor ?

public Node(T t) => (Next, Data) = (null, t);

I am not sure what this means

(Next, Data) = (null, t);
3
  • That's technically called an expression-bodied constructor, see for example C# 7 Expression Bodied Constructors.
    – dxiv
    Aug 9, 2020 at 7:47
  • 1
    @dxiv: Overall it's an expression-bodied constructor, but that (Next, Data) = (null, t); part isn't specific to expression-bodied constructors - it just happens to often be used with them.
    – Jon Skeet
    Aug 9, 2020 at 10:56
  • @JonSkeet Right of course, thanks for setting that straight.
    – dxiv
    Aug 9, 2020 at 20:04

1 Answer 1

5

It's a mixture of:

  • A tuple literal (the (null, t) part)
  • A deconstruction (the (Next, Data) = ... part)

It's effectively this:

public Node(T t)
{
    Next = null;
    Data = t;
}

... but written as a single assignment expression, which means you can use it as an expression-bodied member.

It's odd the first time you see it, but when you're used to it it's a wonderful way of writing simple constructors that just copy parameter values into fields and properties.

5
  • Why couldn't they do this ? public Node(T t) => Next =null; Data = t; or is that an invalid expression body ?
    – MistyD
    Aug 9, 2020 at 19:22
  • @MistyD: Yes, it's invalid because that's two statements. You'd need a regular block body for that. And yes, you absolutely can do that... it's just more verbose.
    – Jon Skeet
    Aug 10, 2020 at 5:51
  • Does it have any kind of performance hit when you do it with deconstruction or it is the same performance like the old way? Aug 29, 2020 at 18:15
  • 1
    @EfthymiosKalyviotis: I believe the compiler actually recognizes this particular pattern and emits exactly the same IL as the "old-style" code.
    – Jon Skeet
    Aug 29, 2020 at 18:17
  • Of curiosity, I tried to de-compile both cases with JetBrains DotPeek and I took slightly different results (although I didn't know how to compare the IL). imgur.com/a/a1UU25L Aug 29, 2020 at 18:58

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.