0

I'm trying to initialize properties of an object I am creating with the values of a named tuple.

Something like this

public Person DoIt() {
  return new Person {
    (First, Last) = GetFirstAndLast(id)
  };
}

public (string first, string last) GetFirstAndLast(int id) {
  return ("First name", "Last name");
}

I know I can achieve the same effect by doing this, but I don't want to use an extra variable.

public Person DoIt()
{
    var (first, last) = GetFirstAndLast(0);
    return new Person
    {
        First = first,
        Last = last
    };
}

comecme
  • 6,086
  • 10
  • 39
  • 67
  • 2
    Your proposed syntax is simply not a part of the language; you can't deconstruct tuples into an object initializer. Closest you can get is `Person result = new(); (result.First, result.Last) = GetFirstAndLast(id); return result;` which I think is short and clear enough, aside from more contrived options like implicit conversion operators and a constructor that takes a tuple. – Jeroen Mostert Sep 12 '22 at 15:52
  • 1
    Is there a reason `GetFirstAndLast` returns a tuple rather than return a `Person`? I know this is an example, but what's the real world scenario where this would be useful rather than simply use the correct type in the first place? – Xerillio Sep 12 '22 at 16:01
  • @Xerillio In the real life situation the method needs to return two values (an enum value and a string). The type that uses the results creates a new instance of a type and fills two properties with the result of the GetFirstAndLast method. It also initializes other fields from the object initializer. – comecme Sep 13 '22 at 14:50

1 Answers1

0

You can't do that inside the object initializer but you can do similar inside the constructor

public class Person
{
    public string First { get; } //with(out) set or init
    public string Last { get; } //with(out) set or init
    public Person((string, string) _)
        => (First, Last) = _;
}
public Person DoIt()
  => new Person(GetFirstAndLast(id));
Peter Csala
  • 17,736
  • 16
  • 35
  • 75