-1

I'm learning C# and am completely new to it so I'm sorry if this seems like a really simple question.

I've just watched a tutorial explaining how you can use the out parameter to return multiple values from a method. However, I don't really understand how it works in practice. The example they gave is:

using System;

namespace UsingOut
{
    class Program
    {
        static void Main(string[] args)
        {
            string statement = "GARRRR";
            string murmur = Whisper(statement, out bool marker);
            Console.WriteLine(murmur);
        }

        static string Whisper(string phrase, out bool wasWhisperCalled)
        {
            wasWhisperCalled = true;
            return phrase.ToLower();
        }
    }
}

However, I don't see how this is returning multiple values? It looks like it's just returning the string?

Please can someone give me a really simple explanation of when to use out and what it actually does?

Thanks so much

juemura7
  • 411
  • 9
  • 20
  • 2
    `wasWhisperCalled = true;` your bool param is also set/changed/modified and returned – Ňɏssa Pøngjǣrdenlarp Jul 28 '19 at 16:04
  • Thank you @ŇɏssaPøngjǣrdenlarp :) I don't see where is it returned?? – juemura7 Jul 28 '19 at 16:13
  • Setting `wasWhisperCalled = true` will also set `marker = true` in the calling method. You could also use a `ValueTuple` as return value: `static (string, bool) Whisper(string phrase) { return (phrase.ToLower(), true); }` and call it with `(string murmur, bool marker) = Whisper(statement);` – Olivier Jacot-Descombes Jul 28 '19 at 16:50
  • 1
    Stack Overflow is not a tutorial site. See marked duplicate for info on the difference between return values and by-reference parameters, such as those that use `out`. That said, note that a value being "returned" simply means that the caller of the method has the value. The `out` parameter isn't "returned" via the same mechanism as a value returned using the `return` statement, and then which is the value of the method call expression itself after the method returns; instead, it's stored directly into the variable that was passed via `out` in the first place. But both return values. – Peter Duniho Jul 28 '19 at 17:44

1 Answers1

0

Well don’t know how if you know C++ but it is quite similar to C++ where you can pass a parameter to function as a reference. So, function is indeed returning just one string, but it will also set the value of wasWhisperCalled. So if wasWhisperCalled was false before function call, then after the function call it will be set to true. Hope this clarifies this a little bit more.

golobitch
  • 1,466
  • 3
  • 19
  • 38