FAQ: Method Output - Using Out

Hi
Forgot to mention,
The code above basically grabs the three values from the method MyMethod which are
isMaleToMain, nameIsToMain, ageToMain and passes them to the main where they are stored in the new variables called isMale, nameIs and age
Then it prints out isMale, nameIs and age to the console with some extra text

the output is :
is this person a male: True
This persons name is: LonelyOtaku
How old is this person: 21

The difference between return and out:
Return can only return one value.
Out can return as many values as you would like.

You can use return as well as out together like in the lesson, but in the lesson although they pass a value using out, for some reason they didnt use it.

Sorry if I’m over explaining, your comment didnt leave me alot to go on.

1 Like

What is the Console.ReadKey() method?

Console.Readkey(); is used to to capture user input (By input I mean the user pressing a key on the keyboard)
It can also be used to stop the console window from closing straight away before you have a chance to read what has been printed to it. When used like above the console window wont close until a user has pressed a key on the keyboard. It is very useful when coding in visual studio. You can also use Console.ReadLine(); to acomplish the same thing.

What is the difference between Console.ReadKey() and Console.ReadLine()? Am I spelling the .ReadKey() right. You wrote in your posts .Readkey() and .ReadKey(). Which one is correct?

The version with the capital K is correct.

There’s a slight difference between the line and key version when used to stop the console window from closing. The line version wont close the console window until the user presses the enter key. the key version will close the console window as soon as any key is pressed.

When used to capture user input from the keyboard. The line version will capture everything the user types until the enter key is pressed, the key version will only capture the first key that was pressed without waiting for the user to press enter.

The key version is useful for giving the user options such as press a, b or c to continue.
the line version is useful for grabbing data, such as please enter your name followed by the enter key.

In the code I entered originally to help you with your problem, it was used to make sure the console window stayed open, so that the data printed to it could be read before closing. Coding in Visual Studio is different to using this website. I recommend you give it a go, it highlights problems such as using a lower case K when it should be a capital. Thanks to its intellisense.

Hope this helps

1 Like

Even if I don’t use it or capture user input the window still stays open.
Look:
Code:

using System; namespace UsingOutCode { class Program { /* To return more than one value from a method: For each value we want to return we have to declare the variable type and give it a name. Each one has to be seperated with a comma and also has to have the out keyword before it we do this within the method parenthesis */ static void MyMethod(out bool isMaleToMain, out string nameIsToMain, out int ageToMain) { //We have set the values here in the method ageToMain = 21; nameIsToMain = "LonelyOtaku"; isMaleToMain = true; } static void Main(string[] args) { /* To get those returned values from the method called MyMethod: First we call the method using its name after the method name and inside of the parenthesis We have to create the same number of variables being returned by the method that we are calling. Making sure the variable types i.e string, int match. You can use the same variables names like isMaleToMain from the method you are calling to pass the values into if you wish, I've chosen to name them differently here And again you have to use the out keyword before each one */ //Calling the method creating variables to pass the values from //MyMethod into MyMethod(out bool isMale, out string nameIs, out int age); /*now we can use these variables that we have created to store the returned values in from MyMethod. */ //Here we are printing the returned values out Console.WriteLine($"is this person a male: {isMale}"); Console.WriteLine($"This persons name is: {nameIs}"); Console.WriteLine($"How old is this person: {age}"); // Console.ReadKey(); } } }

.

At VS it stays open:


See it doesn’t close automatically but when I press a key even without the Console.ReadKey().

Sorry it’s my first time logging in since your post. In visual studio there are many settings.

There is a setting located in Tools>Options>Debugging>General>‘Automatically close the console when debugging stops’

If someone has this setting selected the window would close unless there is Console.ReadKey();
or Console.ReadLine(); And you wouldn’t get to see everything that is printed. Debugging is what happens when you click the green play button or the F5 key. It’s always best to include a Console.Readkey(); or Console.ReadLine(); in my opinion at the end of your code when sharing, in case they have this option selected in their setup.

Just like you I’m a beginner, I finished the C# course 30 days ago and have had 27 days off since. Unfortunately, I can’t dedicate as much time to this as I would like because of other commitments.

I started answering people’s questions in the forums because not many others were.

Hopefully you decide to do the same and give something back to the coding community.

I just wanted to post in case others were having the same troubles I was at understanding what was going in in the code in this lesson.

out is just another way of saying “This is a second, third, or fourth value we want to assign in the method.” and has zero impact on making the phrase capitalized or not, you could just leave it all out altogether.

I think the lesson would have been better at explaining out if the out used in the lesson was more meaningful or used something other than bool even.

The Concept Review page made out make significantly more sense an I advise people to look at it.

i have a couples of weeks trying to understand this but i have been able to , i think they should have also a video explaining the class that’d really useful a helpful for all the student fir sure!

There’s a comfort to coming here and seeing that I was not the only person who was lost. Oddly, I got all of the related exercises right, but I don’t feel confident that I understood the concept.

I am losing my mind trying to understand this exercise. Can someone please explain to me what the boolean is doing? I have no idea why the boolean is there or what its purpose is. I am reading all of the explanations in the exercises but dont see anything that explains why the boolean is needed or how it works.

In the exercise, the boolean hasn’t been used to accomplish any task, except for relaying information from the Whisper method to the Main method.
The motivation for using the out parameter in this particular exercise is to relay more information than possible with just a single return statement. We want to accomplish two things. We want to convert a string to lowercase AND we also want a true/false answer as to whether the Whisper method was called. If we tried to do something like

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

it won’t work. We will never get to the second return statement, because we will exit the Whisper method when we encounter the first return statement. Out parameters allow us a way around this issue.
In the following snippet,

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

we are specifying that the Whisper method will have an out parameter of boolean type
out bool wasWhisperCalled
Now we make a call to the Whisper method: ---------> Whisper("GARRRR", out bool flag)
The first argument "GARRRR" will be assigned to the phrase parameter.
The second argument out bool flag will be assigned to the out bool wasWhisperCalled parameter.
wasWhisperCalled will act as an alias for flag. That means if we change the value of wasWhisperCalled, we will automatically change the value of the flag variable.
Inside the Whisper method, when we make the assignment wasWhisperCalled = true;, the value of flag will also become true. flag is outside the Whisper method and yet we have changed it from within the Whisper method without using the return keyword (Had we used the return keyword, we would have exited the method and would have failed to return the lowercase string).
If within the Whisper method, we make the assignment wasWhisperCalled = false;, then flag will also be set to false because wasWhisperCalled is acting as an alias for flag.
In the exercise, we don’t do anything with flag, but we could do something with it if we wanted. If you log the flag variable to the console in Main, you will see that indeed its value matches the assignment we made in the Whisper method.
You may also want to check out the example in the cheatsheet with the heading “Out Parameters”

Thanks for the detailed answer. I think I still dont understand fully. Why is the bool not printed when murmur is called with the WriteLine? Since murmor is the same as whisper and whisper has both the string and the boolean in, why is only the string printed and not the boolean?

Also I dont understand the connection between phrase and statement. Why does statement get lowercased when phrase is lowercased.

I don’t understand what you mean by murmur/murmor?

When we make the call Whisper("GARRRR", out bool flag), then within the Whisper method we set wasWhisperCalled to true. Since wasWhisperCalled is just an alias for flag, so flag (which is outside the Whisper method) will be set to true as well.
However, this is not the same as using the return keyword. The only value explicitly “returned” by the Whisper method is return phrase.ToLower(); which means that only ‘garrrr’ will be explicitly returned. wasWhisperCalled will indeed change flag but only one value is being explicitly returned by the method and that is lowercase phrase. If we look at the signature of the Whisper method, we see

static string Whisper(...

that the return type is string only.

Suppose in the Main method we did something like:

// Single Line Version
Console.WriteLine(Whisper("GARRRR", out bool flag));

// The above can be broken into:
string word = "GARRRR";  // word will be GARRRR
string result = Whisper(word, out bool flag); // result will be "garrrr" and flag will be set to true
Console.WriteLine(result); // "garrrr" will be printed to the console
// After the above code, word will still be "GARRRR", result will be "garrrr", flag will be true. 
// Only "garrrr" will be printed to the console.

// If we don't want to store result in some variable and only
// want to print the result, then the single line version
// accomplishes our goal without the need of declaring and initializing
// the 'result' variable.

I assume you are talking about the snippet in Step 2 of the exercise

string statement = "GARRRR";
Whisper(statement, out bool marker);
// should return  "garrrr" and set marker to true;

The return value of Whisper will be the lowercased phrase. In the above snippet, marker will be set to true, but statement will still be “GARRRR”. In the above snippet, nothing is done with the return value so it doesn’t accomplish anything useful other than setting marker.
If we want to do something useful, then we could do:

string statement = "GARRRR";
// If we simply wanted to print the lowercase string 
Console.WriteLine(Whisper(statement, out bool marker));  // will print "garrrr"

// If we want to replace the original statement with lowercase version 
statement = Whisper(statement, out bool marker); // Now statement will be "garrrr"

// If we don't want to replace statement, we can assign lowercase version to some other variable
string myVar = Whisper(statement, out bool marker);

I am talking about the connection between statement and phrase.

I dont get why the string phrase is not string statement, what connects statement and phrase? String statement is the line what we want to print to the console, garrrr. String phrase is what gets lowercased. I dont see anywhere anything that makes phrase = to statement.

Suppose we have a method whose name is Greeting. It has one string parameter called username. It prints a message when the Greeting method is called. The method may look like:

static void Greeting(string username) {
    Console.WriteLine($"Hello {username}! Welcome to the program.\n");
}

Now suppose, we make calls to this method from our Main method.

static void Main(string[] args) {
    Greeting("Jack");
    
    string someone = "Ben";
    Greeting(someone);

    string anotherName = "abcde";
    Greeting(anotherName);        
}

All of these calls are valid and the following will be printed to the console:

Hello Jack! Welcome to the program.

Hello Ben! Welcome to the program.

Hello abcde! Welcome to the program.

Whatever string is passed to the Greeting method will be assigned to the parameter called username. This is very useful because it allows us abstraction and re-use of the method. We don’t care about the name of the value being passed in to the method. Whatever it may be called outside the method doesn’t matter to us. Within our Greeting method, we will simply assign that value to the parameter named username. That way we don’t have to change our method for different inputs.
A function call from Main like

string username = "Harry";
Greeting(username);

will work, but we are not constrained that the argument name must match the parameter name. As long as the argument’s data type matches the data type of the parameter, it will work. In our case, as long as we pass a string (whatever we may choose to call it), it will be assigned to username within our method. If we pass something other than a string, then we will get an error. If we pass the wrong number of arguments or the wrong data types, then we will get an error. (In the above example. the variable username in Main has a different scope than the parameter username of the Greeting method, so even if you re-assign some other string to username in the Greeting method, the username variable in Main will remain unaffected. If we use out, then changes can be made which affect variables outside the method)

With the above in mind, hopefully the connection between statement and phrase makes sense.

Hello guys,

I have a simple question and that is do you neeeeed to put the line of code that relates to the out parameter in the method. Idk if my wording is clear but this is what I mean :


static string Whisper(string phrase , out bool wasWhisperCalled)
    {
      wasWhisperCalled = true; // does this need to always go here? //
      return phrase.ToLower();
    }

It doesn’t have to be the first line of the method. but it must be assigned a value before the return statement. If the method isn’t going to assign any value, then there is no point in having an out parameter.


// This won't work because we will return from the method before
// we can assign a value to the out parameter.
static string Whisper(string phrase , out bool wasWhisperCalled)
    {
      return phrase.ToLower();
      wasWhisperCalled = true;
    }

// This will work
static string Whisper(string phrase , out bool wasWhisperCalled)
    { 
      ... some code here ...
      wasWhisperCalled = true;
       ... maybe some more code here ... 
      return phrase.ToLower();
    }

As long as you make an assignment to the out parameter before the return statement, it will work. If you omit the assignment, an error will be thrown.

I’m also confused by this. When I try the solution you can change the Boolean to ‘false’ and it still outputs the lowercase ‘garrrr’ but I thought it would either show in caps or output a 0 or something other than exactly the same thing.

Consider the following modification of the code:

using System;

namespace UsingOut
{
  class Program
  {
    static void Main(string[] args)
    {
      bool flag = false;
      Console.WriteLine(flag);
      Console.WriteLine(Whisper("GARRRR", out flag));
      Console.WriteLine(flag);
    }
    
    static string Whisper(string phrase, out bool wasWhisperCalled)
    {
      wasWhisperCalled = true;
      return phrase.ToLower();
    }
	}
}

// The output will be:
False   //Boolean value of flag before method call
"garrrr"  // String value returned by Whisper method
True    // Boolean value of flag after method call

The call to the method Whisper("GARRRR", out flag) explicitly (using the return keyword) only returns the lowercase phrase, but because of the out parameter, we can change the value of the boolean variable flag in Main.
In the exercise, the wasWhisperCalled parameter isn’t meant to decide whether the returned string should be lowercase or uppercase. It is just meant to relay information to Main that yes, the Whisper method was indeed called.