-1

I have this function call:

 GetLabels(phraseSources[seq].Kanji.Trim(), phraseSources[seq].Kana.Trim());

It returns (string, string,string)

How can I put this into three variables, named for example a, b & c?

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • `var (a, b, c) = GetLabels(...);`? https://learn.microsoft.com/en-us/dotnet/csharp/tuples –  Oct 27 '19 at 09:30

2 Answers2

3

there are many ways to do so, first, you can use

Use .NET 4.0+'s Tuple: as mentioned here

For Example:

public Tuple<int, int> GetMultipleValue()
{
     return Tuple.Create(1,2);
}

Tuples with two values have Item1 and Item2 as properties.

or in C# 7 you can do this:

(string firstName, string lastName) GetName(string myParameter)
    {
        var firstName = myParameter;
        var lastName = myParameter + " something";
        return (firstName, lastName);
    }

    void DoSomethingWithNames()
    {
        var (firstName, lastName) = GetName("myname");

    }
prhmma
  • 843
  • 10
  • 18
2

Method 1 (Pass by Reference)

As C# is like C language, it supports references. You can create 3 strings in main (or wherever you call this function) and pass their references:

string a, b, c;
GetLabels(phraseSources[seq].Kanji.Trim(), phraseSources[seq].Kana.Trim(), ref a, ref, b, ref c);

You also have to change function, so that it receives those three variables. Then assign those references needed values, instead of return.

Method 2 (Return Object)

You also can create an object in function (for ex.: array, tuple etc.) and return it. After function call, disassemble that object and store needed values inside of your strings.

I would recommend you to use first method, as it is more memory efficient (otherwise, you create new object and its copy)

Method 3 (Return multiple objects in C#7) (solution by @phalanx)

(string firstName, string lastName) GetName(string myParameter)
    {
        var firstName = myParameter;
        var lastName = myParameter + " something";
        return (firstName, lastName);
    }

void DoSomethingWithNames()
{
    var (firstName, lastName) = GetName("myname");
}

I just feeled that combining all solutions togehter is better idea))

Miradil Zeynalli
  • 423
  • 4
  • 18