Methods:Methods Out: Lesson 4 Explaination

I was able to work my way through the Method Out “out” section (lesson 4 of methods), but I am really unsure of what exactly I was doing. Could someone give me a for dummies explanation of what is going on here? Thank you!

The code I wrote btw is below:

using System;

namespace OutParameters
{
class Program
{
static void Main(string args)
{
string ageAsString = “102”;
string nameAsString = “Granny”;
int ageAsInt;
bool outcome;
outcome = Int32.TryParse(ageAsString, out ageAsInt);
Console.WriteLine(outcome);
Console.WriteLine(ageAsInt);

  int nameAsInt;
  bool outcome2;
  outcome2 = Int32.TryParse(nameAsString, out nameAsInt);
}    
}

}

https://www.codecademy.com/courses/learn-c-sharp/lessons/csharp-method-output/exercises/out

Hi, and welcome!

out is a way in C# to return more than one information from a method.
The variable with the out keyword will contain the value set in the method after the execution of this one.

Let’s write an example :slight_smile:

You have this method in C#:

public int MyMethodDoingStuff(string name, int age)
{
  age = age * 2;
  return age + 5;
}

If I’m calling this method:

int myAge = 10;
int result = MyMethodDoingStuff("patmol", myAge);

The value of result will be 25 and the value of myAge after the call will still be 10 (as the value was passed by value - or copy).

Let’s write the same method but with the out modifier.

public int MyMethodDoingStuff(string name, out int age)
{
  age = age * 2;
  return age + 5;
}

And let’s call it:

int myAge = 10;
int result = MyMethodDoingStuff("patmol", out myAge);

The value of result is still 25 but the value of myAge after the call is now 20! With other words, the method changed the value of the paramter (the parameter was passed by reference)

1 Like

Oh ok that makes sense thank you! So out is beneficial for when you return more than one information from a method and changing the original value of parameters. That’s the part that wasn’t making sense of why you would want to use out. I appreciate the explanation!