0

So, I'm not sure if something like this is even possible. Maybe? Just curious...

// Initial values of the strings.
string variable1 = "Something", variable2 = "SomethingElse";

// New values for the strings. ** LEFT OF ASSIGNMENT OPERATOR WON'T COMPILE **
(variable1, variable2) = DoSomething(variable1, variable2);

// Method to modify the initial strings.
public List<string> DoSomething(string v1, string v2)
{ ...; return new List<string> { v1, v2 }; }
midoriha_senpai
  • 177
  • 1
  • 16
  • 1
    [That feature](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#tuples) is new to C# 7 - it won't work in any version older than that. – D Stanley Aug 24 '17 at 19:33
  • Personally, I know that feature only from the LISP programming language (`multiple-value-setq` form). Mainstream languages can only return one object from a function and assign one variable in a statement. Oh, how I miss that LISP feature... – Ralf Kleberhoff Aug 24 '17 at 20:43
  • Reopened because the other question only initializes new variables from the tuple and this one asks about assigning tuple results into multiple existing variables/lvalue expressions. – Ben Voigt Nov 06 '19 at 16:40

1 Answers1

2

You probably are asking about something syntactically similar to

C#7 Tupples

Nice property of it, apart of shorter declaration than usual Tuple<T>, is that you can have named elements, which is a big deal from point of view code readability and maintenance.

If you are asking about only semantics of implementation: returning 2 double values at once with C# today, you obviously can use Tuple<T>, like

Tuple<double, double> = DoSomething();

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • Thanks for your reply, @Tigran. Tuples are definitely something I'll be looking into, but I don't think it quite satisfies the requirements of this question. I believe I would still have to access the tuple by index in order to assign to the variables. The goal would be to assign directly to the variables using what is returned by the method. – midoriha_senpai Aug 24 '17 at 20:02
  • 2
    @GregGreenleaf: why don't use `out` or `ref` then ? – Tigran Aug 24 '17 at 20:03
  • I looked a bit more into tuples, @Tigran, and I think that you're right. Tuples have a built in ability called a deconstructing assignment, which fits perfectly into what I was wondering. So thank you for pointing me in the right direction. `(first, middle, last) = LookupName(id2); // deconstructing assignment` – midoriha_senpai Aug 25 '17 at 15:54
  • 1
    @GregGreenleaf the one I wrote first is only for `c#` 7 though. – Tigran Aug 25 '17 at 15:56