-1

I am new to coding and C# and I was wondering if a method gets called multiple times if you use tuples as return value?

This description may lack because I am no native to the english language so here is some example code:

public static (bool Correct, string Output) MyMethod1(int MyArgument)
{
    // Do something
    return (true, MyOutput);
}

public void Execute()
{
    if (MyMethod1(100).Correct)
    {
        Console.WriteLine(MyMethod1(100).Output);
    }
}

So I am wondering if we go through the whole method MyMethod1 twice now or just once because the argument is the same.

Thank you very much.

Also please let me know if I did anyhing wrong, posting this. As I am also new to SO.

Luna
  • 63
  • 2
  • 6
  • 4
    If you have two calls to a method, it will be called twice. Tuples have nothing to do with it. Just as you would for any expression, store its result in a variable if you only want to evaluate it once: `var (correct, output) = MyMethod1(100);` – Aluan Haddad Jan 14 '21 at 11:28
  • 1
    Indeed, the method is here called twice, and if it is not expected, you must use a variable to store the result so that you can use it after the call to use it for the test condition and the process. –  Jan 14 '21 at 11:36
  • 2
    Id you ask someone to tell if they can get something for you, then ask them again to get it. Did you ask the person twice? Or what if you ask someone to get something, then you check the results, then inspect it? – TheGeneral Jan 14 '21 at 11:49
  • 1
    You are worrying (or hoping) that the compiler can optimize the calls (remembering the first result) because at first glance they are identical; The compiler MUST NOT assume such behavior for two reasons: 1) it depends on method implementation, whose result can depend on additional/external data. 2) it is responsibility of the developer to perform such optimization, if she want so.. by the way the jitter can optimize out all the calls by inlining the method instructions; in some cases, the method instructions can even be replaced by the result itself, if it is a constant value known in advance – Rubidium 37 Jan 14 '21 at 12:00

1 Answers1

1

To have your method executed only once in this case you should store the retrieved result of the method like so:

public static (bool Correct, string Output) MyMethod1(int MyArgument)
{
    // Do something
    return (true, MyOutput);
}

public void Execute()
{
    (bool correct, string output) result = MyMethod(100);
    if (result.correct)
    {
        Console.WriteLine(result.output);
    }
}
  • 2
    Since the method already returns a named value tuple, [prefer](https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c-sharp) writing [`var`](https://learn.microsoft.com/fr-fr/dotnet/csharp/language-reference/keywords/var) `result = MyMethod(100);`. –  Jan 14 '21 at 11:40