Use Tuple values in Object initalizer syntax

194 Views Asked by At

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
    };
}

1

There are 1 best solutions below

0
Peter Csala On

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));